Postman for dummies
Types of variables
- Global Variables: Useful for values that are used frequently across multiple collections and environments.
- Scope: Available across all collections, environments, and requests.
pm.globals.set("globalVar", "globalValue");
console.log(pm.globals.get("globalVar"));
2. Collection Variables: Useful for values that are specific to a collection but need to be shared across multiple requests within that collection.
- Scope: Available to all requests within a specific collection.
pm.collectionVariables.set("collectionVar", "collectionValue");
console.log(pm.collectionVariables.get("collectionVar"));
3. Environment Variables: Useful for managing different configurations for different environments (e.g., development, staging, production).
- Scope: Available to all requests within a specific environment.
pm.environment.set("envVar", "envValue");
console.log(pm.environment.get("envVar"));
4. Local Variables:
- Use Case: Useful for temporary values that do not need to be shared outside of a single request or script.
- Scope: Available only within the scope of a single request or script.
var localVar = "localValue";
console.log(localVar);
5. Data Variables: Useful for running collections with different sets of data (e.g., CSV or JSON files).
- Scope: Available only during the execution of a collection run with data files.
console.log(data.variableName);
Types of Authorizations
- No Auth: No authentication is required for the request.
Real-Time Example:
Public APIs like weather APIs (e.g., OpenWeatherMap’s free endpoints) often don’t require authentication for basic queries.
- Use Case:
Fetching public data, such as weather forecasts or currency conversion rates.
eg.
curl "https://api.openweathermap.org/data/2.5/weather?q=London"
- 2. API Key: Use an API key to authenticate requests. The key can be sent in the query parameters or headers.
Real-Time Example:
Google Maps API or Stripe Payment Gateway. The API key is included in headers or query parameters for authentication.
Use Case:
Used for tracking API usage or providing basic security for public APIs.
eg. Use in Query parameter
curl "https://maps.googleapis.com/maps/api/geocode/json?address=New+York&key=YOUR_API_KEY"
OR in Header
curl -H "X-API-KEY: YOUR_API_KEY" https://api.example.com/data
3. Bearer Token: Use a token to authenticate requests. The token is usually sent in the Authorization header.
Real-Time Example:
GitHub API requires a personal access token in the Authorization
header.
Use Case:
Secure communication in REST APIs for accessing private resources after user authentication.
eg
curl -H "Authorization: Bearer YOUR_TOKEN" https://api.github.com/user/repos
4. Basic Auth: Use a username and password to authenticate requests. The credentials are encoded in Base64 and sent in the Authorization header.
Real-Time Example:
Legacy systems or internal APIs might use this for simplicity. For instance, a private Jenkins server API.
Use Case:
Simple authentication for systems where encryption (HTTPS) is guaranteed.
eg.
curl -u username:apitoken https://your-jira-instance.atlassian.net/rest/api/3/issue
5. Digest Auth: Similar to Basic Auth but more secure. Uses a challenge-response mechanism to authenticate requests.
- Real-Time Example:
Some web applications, such as Apache servers configured with Digest Auth, use this for additional security. - Use Case:
Used in environments where credentials need to be hashed to prevent replay attacks.
eg.
curl --digest -u username:password https://api.example.com/secure-data
6. OAuth 1.0: Use OAuth 1.0 to authenticate requests. Requires consumer key, consumer secret, access token, and token secret.
Real-Time Example:
Twitter API (legacy). Applications authenticate via OAuth 1.0 to post or retrieve data on behalf of users.
- Use Case:
Secure API access for older systems requiring both client and user credentials.
eg.
curl --request "GET" "https://api.twitter.com/1.1/statuses/user_timeline.json" \
--header "Authorization: OAuth oauth_consumer_key='key', oauth_token='token', ..."
7. OAuth 2.0: Use OAuth 2.0 to authenticate requests. Requires client ID, client secret, access token, and other optional parameters.
Real-Time Example:
Google APIs (e.g., Gmail, Google Drive) or Facebook Graph API for third-party app integrations.
- Use Case:
Secure authentication and authorization for modern applications, allowing delegated access without sharing credentials.
eg.
curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" https://www.googleapis.com/oauth2/v1/userinfo
8. Hawk Authentication: Use Hawk to authenticate requests. Requires Hawk credentials and other optional parameters.
- Real-Time Example:
APIs like Kinto (Mozilla’s JSON storage service) use Hawk for verifying requests via cryptographic signatures. - Use Case:
Secure APIs where requests must be verified for integrity without exposing credentials.
eg.
curl --header "Authorization: Hawk id=\"id\", mac=\"mac\", ts=\"timestamp\"" https://api.example.com/resource
9. AWS Signature: Use AWS Signature to authenticate requests to AWS services. Requires access key, secret key, region, and service name.
- Real-Time Example:
AWS S3 APIs require AWS Signature v4 for actions like uploading files or querying objects. - Use Case:
Authenticating and signing requests to AWS services with strict security.
eg.
aws s3api list-buckets --region us-west-2 --profile my-profile
10. NTLM Authentication: Use NTLM (Windows-based) authentication. Requires username, password, and optional domain and workstation.
- Real-Time Example:
Microsoft Exchange Web Services (EWS) or internal enterprise systems that use Windows authentication. - Use Case:
Secure enterprise-level APIs where user credentials are validated against Active Directory.
eg.
curl --ntlm -u username:password https://example.com/secure-endpoint
Methods
In Postman, you can use various HTTP methods to interact with APIs. Each method serves a different purpose and is used to perform specific actions on the server. Here are the main HTTP methods available in Postman:
- GET:
- Purpose: Retrieves data from the server.
- Example: Fetching user details.
2. POST:
- Purpose: Sends data to the server to create a new resource.
- Example: Creating a new user.
3. PUT:
- Purpose: Updates an existing resource on the server.
- Example: Updating user details.
4. PATCH:
- Purpose: Partially updates an existing resource on the server.
- Example: Updating a user’s email address.
5. DELETE:
- Purpose: Deletes a resource from the server.
- Example: Deleting a user.
6. HEAD:
- Purpose: Similar to GET, but only retrieves the headers of the response.
- Example: Checking if a resource exists.
7. OPTIONS:
- Purpose: Describes the communication options for the target resource.
- Example: Checking allowed HTTP methods for a resource.
8. CONNECT:
- Purpose: Establishes a tunnel to the server identified by the target resource.
- Example: Used for SSL tunneling.
9. TRACE:
- Purpose: Performs a message loop-back test along the path to the target resource.
- Example: Debugging and diagnostics.
HTTP status codes
Standardized codes returned by the server to indicate the result of a client’s request. They are grouped into five classes based on their first digit. Here are the main categories and some common status codes:
- 1xx: Informational
- 100 Continue: The server has received the request headers, and the client should proceed to send the request body.
- 101 Switching Protocols: The requester has asked the server to switch protocols, and the server has agreed to do so.
2. 2xx: Success
- 200 OK: The request was successful, and the server returned the requested resource.
- 201 Created: The request was successful, and a new resource was created.
- 202 Accepted: The request has been accepted for processing, but the processing is not complete.
- 204 No Content: The request was successful, but there is no content to send in the response.
3. 3xx: Redirection
- 301 Moved Permanently: The requested resource has been permanently moved to a new URL.
- 302 Found: The requested resource is temporarily located at a different URL.
- 304 Not Modified: The resource has not been modified since the last request.
4. 4xx: Client Errors
- 400 Bad Request: The server could not understand the request due to invalid syntax.
- 401 Unauthorized: The client must authenticate itself to get the requested response.
- 403 Forbidden: The client does not have access rights to the content.
- 404 Not Found: The server cannot find the requested resource.
- 405 Method Not Allowed: The request method is known by the server but is not supported by the target resource.
- 409 Conflict: The request could not be completed due to a conflict with the current state of the resource.
5. 5xx: Server Errors
- 500 Internal Server Error: The server encountered an unexpected condition that prevented it from fulfilling the request.
- 501 Not Implemented: The server does not support the functionality required to fulfill the request.
- 502 Bad Gateway: The server, while acting as a gateway or proxy, received an invalid response from the upstream server.
- 503 Service Unavailable: The server is not ready to handle the request, often due to maintenance or overload.
- 504 Gateway Timeout: The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server.
Query parameters
Key-value pairs that are appended to the end of a URL to pass data to the server. They are used to filter, sort, or modify the data returned by the server. Query parameters are added to the URL after a question mark (?
) and are separated by an ampersand (&
) if there are multiple parameters.
Example URL with Query Parameters
https://example.com/api/users?name=JohnDoe&age=25
In this example:
name
is a query parameter with the valueJohnDoe
.age
is a query parameter with the value25
.
Pre-request scripts in Postman are scripts that are executed before the actual request is sent. They are used to set or modify environment variables, add headers, or perform any setup required for the request. These scripts are written in JavaScript and can be used to dynamically alter the request based on certain conditions.
Pre-request Script
Scripts that are executed before the actual request is sent. They are used to set or modify environment variables, add headers, or perform any setup required for the request. These scripts are written in JavaScript and can be used to dynamically alter the request based on certain conditions.
// Add a custom header
pm.request.headers.add({key: "Custom-Header", value: "HeaderValue"});
// Log a message to the console
console.log("Pre-request script executed");
Common Use Cases
- Setting Authentication Tokens: Automatically set authentication tokens before sending the request.
- Dynamic Parameters: Generate dynamic parameters or values that need to be included in the request.
- Conditional Logic: Execute conditional logic to modify the request based on certain conditions.
- Data Preparation: Prepare data or payloads that need to be sent with the request.
The Tests tab
Allows you to write scripts to validate the response of an API request. These scripts are executed after the response is received and can be used to perform various checks and assertions on the response data. The scripts are written in JavaScript.
// Check if the response body contains a specific property
pm.test("Response body has property 'name'", function () {
var jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("name");
});
// Check if a header is present in the response
pm.test("Content-Type is present", function () {
pm.response.to.have.header("Content-Type");
});
Common Use Cases
- Status Code Validation: Ensure the response status code matches the expected value.
- Response Time Validation: Check if the response time is within acceptable limits.
- Response Body Validation: Verify the presence and values of specific properties in the response body.
- Header Validation: Confirm that specific headers are present in the response.