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
- 1. Automate Postman API Testing: The Postman testing tool executes tests automatically and ensures they pass or fail based on expected outcomes.
- 2. Dynamic Data Handling: Work with real-time data inputs, manipulate responses, and generate dynamic requests.
- 3. Create Complex Test Scenarios: Chain API requests together, conditionally execute requests, and perform deep data validation.
- 4. Integrate with CI/CD: Automate test execution in continuous integration and delivery workflows using Newman (Postman’s CLI).
The Execution Order Of Scripts
- The pre-request script runs before the request has been sent.
- The post-response script runs after the request has been sent.
Advanced Techniques for Postman Automation API Testing
1. Automating Tests with Test scripts (Pre-Request and Post-Response)
1.1. Pre-request Scripts
a. Purpose:
b. Use Cases:
- Generating dynamic tokens (e.g., OAuth or JWT tokens)
- Setting request headers dynamically
- Adding timestamps or other dynamic data to requests
- Chaining API requests by extracting values from previous responses and passing them to subsequent requests
const timestamp = new Date().toISOString(); pm.environment.set('timestamp', timestamp);
1.2. Post-response Scripts (Previously Known As Test Scripts)
a. Purpose:
b. Use Cases:
- Validating response status codes (e.g., checking if it’s 200 OK)
- Asserting values in the response body
- Checking headers, response times, or any other response attributes
- Storing values from responses for reuse in other requests
- Postman testing tool uses the chai assertion library, which provides a robust set of functions to test API responses.
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
2.1. How Data-Driven Testing Works:
- Prepare the Data: Provide a CSV or JSON file with different sets of input values.
- Parameterize Requests: Use variables in your API request to refer to values from the data file.
- Run the Collection: Postman iterates through each row of data, using the corresponding values in the API request, and runs the tests for each iteration.
- Automated Validation: Postman can validate responses for each data input by using assertions in the test scripts.
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):
b. Set Up Postman Request:
{ "username": "{{username}}", "password": "{{password}}" }
let requestData = pm.iterationData.get("username"); pm.environment.set('dynamicUser', requestData);
c. Add Test Scripts (Optional):
pm.test("Login successful", function () { var jsonData = pm.response.json(); pm.expect(jsonData.status).to.eql("success"); });
d. Run the Collection with Data File:
- Click on the Runner icon in Postman to open the Collection Runner.
- Select the collection or folder containing the API requests.
- Choose the data.csv (or a JSON file) by clicking the Select File button.
- Set the iteration count as necessary. Postman will automatically match each iteration to the rows in the data file.
- Click Start Run to begin testing.
2.3. Benefits of Data-Driven Testing:
- Scalability: You can test multiple cases without manually changing the inputs with API automation using Postman.
- Efficiency: Quickly run tests against large sets of data with a postman testing tool.
- Consistency: Ensure that the API behaves as expected with different input variations.
- Automated Workflow: Postman for API testing simplifies repetitive testing and makes it easier to integrate into CI/CD pipelines.
3. Chaining Requests and Conditional Workflows
pm.test("Login successful, extract token", function () { var jsonData = pm.response.json(); pm.environment.set('authToken', jsonData.token); });
pm.request.headers.add({ key: 'Authorization', value: 'Bearer ' + pm.environment.get('authToken') });
if (pm.response.code === 200) { pm.setNextRequest('Next API Request'); } else { pm.setNextRequest(null); // Stop the workflow }
4. Advanced Response Validation
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'); });
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
newman run collection_name.json -e environment_variable.json -g global_variable.json
newman run collection_name.json -e environment_variable.json -g global_variable.json -d testdata.csv
newman run collection_name.json -e environment_variable.json -g global_variable.json -d testdata.csv --delay-request 10000
newman run collection_name.json -e environment_variable.json -g global_variable.json -d testdata.csv --delay-request 10000 -r htmlextra
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