As API-driven applications become more widespread, robust API testing is more crucial than ever. Postman automation API testing has powerful built-in scripting features that go beyond simple request-response validation. This API testing tools-postman has capabilities,

  • To enable advanced test automation,
  • Allowing users to create dynamic tests,
  • Implement data-driven workflows,
  • and seamlessly integrate with CI/CD pipelines.

This makes the postman testing tool an essential tool for modern API development and testing.

In this blog, we’ll explore how Postman’s built-in scripting can be leveraged for advanced API test automation.

Use of Postman’s Built-In Scripting

Postman’s built-in scripting features (using JavaScript) provide a powerful way to extend the functionality of API testing beyond basic requests. Here are some key reasons to use Postman’s built-in scripting:

The Execution Order Of Scripts

As shown below, the Scripts section has two types: Pre-request and Post-response.
The order of script execution for a single request follows this sequence:

Advanced Techniques for Postman Automation API Testing

Let’s understand deeper with this Postman automation api testing tutorial into how these features can be used for advanced test automation with Postman.

1. Automating Tests with Test scripts (Pre-Request and Post-Response)

Postman Automation API Testing offers two primary types of scripting:

1.1. Pre-request Scripts

a. Purpose:
Pre-request scripts are executed before the API request is sent to the server. They are used to set or manipulate environment or collections variables, generate dynamic values, modify request headers, or add logic that prepares the request for execution. This is particularly useful in scenarios where APIs require authentication or complex parameterization.
b. Use Cases:
Dynamic timestamp in the Pre-request Script postman automation api testing example:
const timestamp = new Date().toISOString();
pm.environment.set('timestamp', timestamp);
This timestamp can then be used as part of the request body, headers, or parameters in the API model.

1.2. Post-response Scripts (Previously Known As Test Scripts)

a. Purpose:
Post-response scripts are executed after receiving the response from the server. These scripts are used to validate responses, check status codes, parse response data, and perform assertions to verify API behavior.
b. Use Cases:
Here’s a simple test script that checks for a successful status code and validates that a particular field exists in the response:
pm.test("Status code is 200", function () {  
	pm.response.to.have.status(200);  
});  
pm.test("Response contains userId", function () {  
	var jsonData = pm.response.json();  
	pm.expect(jsonData).to.have.property('userId');  
}); 

2. Data-Driven Testing with Postman

Postman automated testing allows you to execute API requests multiple times with different sets of input data. This is particularly useful when you need to validate an API with various test cases, using different data inputs for each iteration. Postman automated testing makes this process efficient by using Collection Runner combined with a data file (CSV or JSON) to drive test execution.

2.1. How Data-Driven Testing Works:

2.2. Steps for Data-Driven Testing in Postman:

a. Prepare the Data File:

Prepare a CSV or JSON file with test data.
Here is an example of a CSV file (data.csv):

Also, an example of JSON file (data.json)
b. Set Up Postman Request:
In the API request, replace the actual data values with variables that match the keys in the data file. For example, suppose you have an API request for logging in a user: POST https://api.example.com/loginIn the body of the request (assuming JSON format), you can use Postman variables that will be replaced by values from the data file:
{  
    "username": "{{username}}",  
    "password": "{{password}}"  
}
Here, {username}} and {{password}} are placeholders for the values that will be taken from the CSV/JSON file during each iteration.
Also, the User can set up test scripts to handle different data sets, like this: If the User wants to extract username and password from CSV or JSON file, then
let requestData = pm.iterationData.get("username");  
pm.environment.set('dynamicUser', requestData);
In this example, iterationData refers to the current iteration of the data file, allowing you to extract values for the current API call. Using variables in the request allows you to automate tests with different parameters in each iteration.
c. Add Test Scripts (Optional):
You can add test scripts to validate the response for each data set. For example, checking if the login is successful:
pm.test("Login successful", function () {  
var jsonData = pm.response.json();  
pm.expect(jsonData.status).to.eql("success");  
});
This script checks whether the login API response includes a “status”: “success” field, ensuring that the login attempt was successful.
d. Run the Collection with Data File:
To run the data-driven tests:
2.3. Benefits of Data-Driven Testing:
3. Chaining Requests and Conditional Workflows
One of the most powerful features of API testing tools Postman scripting is the ability to chain requests. This means you can extract data from one API response and use it in subsequent requests, automating complex workflows and test scenarios.
For instance, you can extract a token from a login API and use it in the headers of subsequent requests:
pm.test("Login successful, extract token", function () {  
    var jsonData = pm.response.json();  
    pm.environment.set('authToken', jsonData.token);  
});
Then, in the next request, you can set the token in the headers dynamically:
pm.request.headers.add({  
    key: 'Authorization',  
    value: 'Bearer ' + pm.environment.get('authToken')  
});
In addition, Postman supports conditional workflows using pm.setNextRequest(). This allows you to control which requests should be executed next, enabling automated decision-making based on API responses.
Example of conditional request chaining:
if (pm.response.code === 200) {  
    pm.setNextRequest('Next API Request');  
} else {  
    pm.setNextRequest(null); // Stop the workflow
}
4. Advanced Response Validation
Postman’s scripting enables deep validation of API responses. Beyond checking status codes and basic JSON properties, you can perform complex validations like verifying array lengths, response time, or nested JSON objects.
Here’s a Postman automation API testing example that checks for array lengths and object properties:
pm.test("Array length is greater than 0", function () {  
    var jsonData = pm.response.json();  
    pm.expect(jsonData.items).to.be.an('array').that.is.not.empty;  
});  


pm.test("Nested object contains expected value", function () {  
    var jsonData = pm.response.json();  
    pm.expect(jsonData.user.address.city).to.eql('New York');  
});

You can also verify response times and ensure your API is meeting performance benchmarks:
pm.test("Response time is less than 200ms", function () {  
    pm.expect(pm.response.responseTime).to.be.below(200);  
});
5. Integration with CI/CD Pipelines Using Newman

Postman Automation API Testing doesn’t stop at the GUI. You can execute Postman collections in a CI/CD pipeline using Newman, the CLI tool for Postman. This allows you to run your Postman tests as part of your build pipeline, ensuring that API tests are automated at every stage of development.

To run a Postman collection via Newman:

newman run collection_name.json 
If need to pass environment and global variables with collection
newman run collection_name.json -e environment_variable.json -g global_variable.json
If csv needs to pass
newman run collection_name.json -e environment_variable.json -g global_variable.json -d testdata.csv
To Include delays (in milliseconds) between requests (here added 10ms).
newman run collection_name.json -e environment_variable.json -g global_variable.json -d testdata.csv --delay-request 10000
To generate html report for verification results.
newman run collection_name.json -e environment_variable.json -g global_variable.json -d testdata.csv --delay-request 10000 -r htmlextra 
You can integrate this command in your CI pipeline (Jenkins, GitLab CI, etc.), ensuring that tests are executed every time new code is pushed. Newman also provides detailed reports, which can be customized or integrated with third-party reporting tools.

Conclusion

Postman’s scripting capabilities make Postman for API testing a powerful platform for advanced API test automation. With features like dynamic data manipulation, request chaining, conditional logic, and seamless CI/CD integration, Postman enables QA engineers and developers to build sophisticated, automated testing frameworks.

By harnessing these scripting tools, teams can ensure their APIs are thoroughly tested, reliable, and capable of meeting the performance needs of modern applications. For those aiming to enhance their API testing workflows, mastering Postman’s scripting functionality is an excellent step forward!

At Triveni Global Software Services, we specialize in custom software development solutions, including API development and testing services. Our team is committed to helping you optimize your API testing processes, ensuring your applications are robust and ready for going to market.

Let us partner with you to elevate your API testing to the next level!

Mausami Tandel