Complete Guide to Automated API Testing with Postman
Background
This article assumes readers have a foundational understending of Postman and basic API concepts, including the ability to manually send requests.
Current setup:
- Windows 7 - 64-bit
- Postman version (free edition): Chrome App v5.5.3
Interface variations across versions may exist, but they do not significantly affect functionality.
To achieve automated API testing, several additional considerations beyond manual request simulation are necessary:
- How to validate if an API call was successful
- How to execute multiple APIs in batch and schedule them
- Handling dependencies between APIs (e.g., placing an order requires prior login)
The following sections address these issues systematically.
Validating API Responses
For automation, we need tools or scripts that can assess whether API responses match expectations. Two primary approaches exist:
- Verify HTTP status codes
- Search for specific keywords within response bodies
In Postman, validation logic is implemented in the Tests tab using JavaScript.
Key Variables
Postman provides built-in variables accessible during test execution:
responseCode: Contains the HTTP status coderesponseBody: The raw response data as a stringtests: A key-value pair structure used to define test success/failureresponseTime: Time taken for the request to completepostman: Offers utility functions such as setting global variables and retrieving headers
Example usage:
// Validate status code
tests["Status code is 200"] = responseCode.code === 200;
// Check for keyword in response body
tests["Contains access_token"] = responseBody.has("access_token");
// Compare full response body
tests["Body matches expected"] = responseBody === "expected content";
// Parse JSON and check values
var jsonData = JSON.parse(responseBody);
tests["Value equals 100"] = jsonData.value === 100;
// Validate response time
tests["Response under 200ms"] = responseTime < 200;
Batch Execution
To manage multiple APIs, store all endpoints in a single collection. This allows grouping related requests.
After creating a collection, each request's test conditions can be defined similarly to the example above:
tests["Status code is 200"] = responseCode.code === 200;
Once configured, run the entire collection through the Runner interface.
Configuration Options
- Environment: Switch between different deployment environments
- Iterations: Number of times to run all requests
- Delay: Interval between runs in milliseconds
- Data File: External file containing test parameters
Dynamic Parameter Handling
When running tests repeatedly, static parameters become ineffective. To solve this, utilize dynamic data via external files.
Using Variables
Replace hardcoded values with variables like {{username}} and {{password}}. Assign these in the Pre-request Script section before sending requests:
postman.setGlobalVariable("username", "test1");
postman.setGlobalVariable("password", "123456");
However, this method still uses fixed values. For true variability, use data files.
Data Files
Upload CSV or JSON files to provide different parameter sets per iteration.
CSV example:
username,password
test1,123456
test2,222222
test3,123456
test4,444444
JSON example:
[
{"username": "test1", "password": "123456"},
{"username": "test2", "password": "222222"},
{"username": "test3", "password": "123456"},
{"username": "test4", "password": "444444"}
]
Scheduled Testing
Postman includes a Monitor feature for scheduling recurring tests. Configure frequency and intervals to automate regular checks.
Managing Inter-Request Dependencies
Complex workflows often require sequential API calls. For instance, placing an order depends on a previous login.
Execution Order
Requests with in a collection execute sequentially based on their order in the folder structure.
Custom Flow Control
Use postman.setNextRequest("request_name") to control execution flow. This function works only in collection runs, not individual requests.
Example:
if (responseCode.code === 200) {
postman.setNextRequest("OrderEndpoint");
} else {
postman.setNextRequest("LoginFailureHandler");
}
Data Transfer Between Requests
Pass data between requests using environment variables or globals.
Environment Variables
Set variables in the environment scope for persistent access across requests:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", data.access_token);
Variable Usage
Reference variables in subsequent requests using syntax like {{token}}.
Practical Example
Consider a login endpoint returning an access token and an order endpoint requiring it.
Steps:
- Ensure login request runs first in the collection
- In login request's Tests tab:
if (responseCode.code === 200 && responseBody.has("access_token")) { var parsed = JSON.parse(responseBody); postman.setEnvironmentVariable("token", parsed.token); postman.setNextRequest("PlaceOrder"); } else { tests["Login failed"] = false; } - In order endpoint, use the token:
// Add to header pm.request.headers.add({key: 'Authorization', value: 'Bearer {{token}}'});
Running the collection will correctly process the login, pass the token to the order endpoint, and skip intermediate steps as needed.