Select Page
API Testing

Postman API Automation Testing Tutorial

Being a leading QA Company, we write blogs on all prominent software testing topics and tools using our real-world experience. So stay sharp by subscribing to our Newsletter.

Postman API Automation Testing

Postman is one of the most popular API testing tools and it can perform both manual and automated API testing. So it is a great choice for beginners who are just getting started with API testing to take the first step with manual testing and gradually move towards automation testing. Moreover, Postman has recently introduced Postbot which is an AI assistant within Postman that can make your testing process easier. But in this blog, our primary focus will be on Postman API Automation Testing. Before we get started, let’s list out all the reasons that make Postman a great choice.

Why use Postman for API Automation?

Being a leading automation testing company, we have used many tools for API automation testing and have found Postman to be a great choice due to the below-listed reasons. It actually streamlines the process of API automation by providing a unified platform for designing, testing, and monitoring APIs, thus improving the efficiency and reliability of API development and maintenance.

User-Friendly Interface: Postman offers an intuitive and user-friendly interface, simplifying API work for developers and testers, without requiring extensive coding.

Testing Capabilities: Postman allows you to easily create and execute automated tests for your APIs, including functional, regression, and load testing. You can define test scripts using JavaScript, which offers flexibility and power in crafting test scenarios.

Collections: Postman allows you to organize your API requests into collections, making managing and sharing them with your team easier. Collections can be exported/imported, facilitating collaboration and version control.

Environment Variables: Postman lets you define environment variables, which can be used to parameterize your requests and make them more dynamic. This is particularly useful for testing different environments (e.g., development, staging, production) with the same set of requests.

Pre-request and Post-request Scripts: Postman enables you to run scripts before and after sending requests, allowing you to set up test conditions, manipulate data, or perform cleanup actions.

Integration with Continuous Integration (CI) Tools: Postman can be integrated with CI/CD pipelines, enabling automated testing as part of your development workflow. This ensures that API changes are thoroughly tested before deployment.

Monitoring and Reporting: Postman offers features for monitoring APIs in production, including real-time monitoring, performance testing, and generating reports on API health and performance.

Extensive Documentation: Postman provides comprehensive documentation and resources, including tutorials, examples, and community support, making it easier for users to get started and troubleshoot issues.

Postman API Automation Testing

To ensure you understand the automation testing process without any doubts, we have used a sample scenario where we use all 4 CRUD operations. We have also explained how to run a collection on the whole and generate reports as well.

Create a Collection & Requests

A collection and subsequent requests have to be created first by following the below steps before we get started with Postman API Automation Testing.

  • First up, launch Postman and click on the ‘Create Collection’ button and give a name to the collection eg: API Demo.
  • Now we have to add requests to the collection we created by clicking the three dots in the top right corner.
  • Click on ‘Add request’, enter the name of the request, and click the Save button to create a (POST) request named “Create User”.
  • Similarly, create a few more requests “Get user details”(GET), “Update user details”(PUT), and “Delete User”(DELETE).
  • After creating the collection with CRUD operations, we have to add a URL and request content for each operation.

create collection in postman api automation

Create User

In the “Create User” request, select the POST request method and enter the URL you want to test. In our blog, we have used https://gorest.co.in/public/v2/users. An authentication token has to be added for the above-mentioned API. It can be done so by clicking on the collection name ‘API Demo’ to view the below screen.

user creation in postman

Click on the ‘Authorization’ tab, select the type as Bearer token, and place your token value in the token field

create user in postman

In Body, select raw, select JSON format, and enter the following request body:

Request Body:

{
    "name": "QA Test",
     "gender": "Male",
     "email": "[email protected]",
     "status": "active"
}

Request body in postman api

Now we have to add the test scripts as shown below to verify the response results by clicking the ‘Tests’ tab.

Test Script:

 pm.test("validate status code", function () 
{
  pm.response.to.have.status(201);
});
pm.test("Validate response data", function() 
{
  var data = pm.response.json();
  pm.expect(data.name).to.equal("QA Test");
  pm.expect(data.email).to.equal("[email protected]");
  pm.expect(data.gender).to.equal("male");
});

Once you click on the “Send” button, you will see the response body for the above-mentioned scripts. You can then validate the response with the expectations and click the “Save” button to save the request.

Test script in postman

Test script in postman automation

Get User Details

In the Get user details request, we have to construct the URL using global variables by adding BaseURL and UserID. Global variables serve as general-purpose variables and should be used sparingly, primarily for rapid prototyping needs. They are accessible to all requests within the Postman environment, regardless of the collection they belong to.

To get particular user details, we may need to pass the User ID as a variable, in Postman it is known as “Globals”.

You can create variables by selecting Environments – > Globals as shown below,

get user details in api automation

get user details in postman api

Now when we select the GET request method and URL as “{{BASE_URL}}/{{USERID}}”, the values will be fetched from global variables. As seen previously in our Postman API Automation testing blog, we have to write test scripts for response body validation in the tests tab as shown below.

Test Script:

pm.test("validate status code", function () 
{
  pm.response.to.have.status(200);
});
pm.test("Validate response data", function() 
{
  var data = pm.response.json();
  var userID = pm.globals.get("USERID")
  pm.expect(data.id).to.equal(parseInt(userID)); // Parse userID to integer for comparison
});

After verifying all the details once, click on the Send button will see the response body for the above-mentioned scripts.

Test script in api postman

test script in postman api

Update User Details

Let’s see how we can validate the details that have been updated. In our example, let’s update the username from QA Test to “QA Test001”. In the Update user details request, select the PUT request method and enter the URL as “{{BASE_URL}}/{{USERID}}”

We will update the username to, in the request body update the value, and send the request as mentioned below

Request Body:

{
    "name": "QA Test 001",
     "gender": "Male",
     "email": "[email protected]",
     "status": "active"
}

Test Script:

Write a script to validate if the updated username is reflected in the response body

pm.test("validate status code", function () {
  pm.response.to.have.status(200);
});
pm.test("Validate response data", function() {
  var data = pm.response.json();
  pm.expect(data.name).to.equal("QA Test 001");
});

Click on the “Send” button and you will be able to see the updated response body

test script in api automation

Delete User

So far in our Postman API automation testing tutorial, we have created the user, validated the response, got user information, and validated the response again. Now it’s time to delete the user.

In the Delete User request, select the DELETE request method, for the URL we have the BaseURl and userId already saved in our collection variables, let’s use it directly for the delete user request

Test Script:

  pm.test("status code is 204", function ()
 {
    pm.response.to.have.status(204);
});

Please note that no response body will be displayed for delete requests. So we just have to verify the status code above and click the Send button

postman automation scripts

Collection Runner

We have seen how to run individual requests so far and will be focusing on how to execute a specific collection directly in our Postman API automation testing tutorial. Postman offers a built-in feature known as the Collection Runner within the Postman interface for this very purpose. You can click on the three dots next to your collection and select “Run Collection” to initiate the process.

postman collection runner

Postman’s API automation testing also supports scheduling features that allow you to automate the execution of collections at specific times or intervals. Here’s a brief overview:

collection runner in postman

Setting Up a Schedule: You can create a schedule by navigating to the collection runner, selecting the collection you want to schedule, and then clicking on the “Schedule Runs” button. From there, you can configure the schedule according to your requirements.

Configuring Schedule Parameters: Postman allows you to specify parameters such as the frequency of runs (e.g., daily, hourly), start date and time, and time zone. You can also choose to run the entire collection or select specific folders or requests within the collection.

Monitoring Scheduled Runs: Once a schedule is set up, you can monitor the status of scheduled runs from the Postman dashboard. You’ll be able to see information such as the last run time, the next scheduled run time, and any run failures or errors.

You can also run it manually by clicking on the ‘Run Manually’ option

collection runner postman

Once the tests have been executed for the collection, you will be able to see the results as shown below.

postman collection

Newman CLI Reporting

As we have seen how to perform all the required tests, let’s see how we can create effective reports in Postman using Newman. Newman is a CLI tool that enables running collections directly from the command line interface. It can be achieved if it’s integrated into a CI/CD pipeline remotely or executed locally on your CLI. You can download Newman from NPM.

After installation, you’ll have to export both your collection and global variables. Let’s see how to do that in our Postman API Automation testing tutorial.

postman report

postman api report

Navigate to the directory where the collection is exported in your CLI and execute the below command

 newman run collection name.json  --globals global variable name.json --env-var "token=YOUR_BEARER_TOKEN"

Once you execute the above command, you will be able to see a report as shown below.

postman newman report

Newman HTML Reporting

If you would like to generate HTML reports, we’ve got that covered as well in our Postman API Automation testing tutorial. First, you’ll have to complete all the prerequisites listed below.

Pre-Requisites:

  • Node.js – Download and Install the Node.js.
  • Newman – Install Newman from the Command Line using the command
    npm install -g newman
    
  • Newman reporter – Install Newman reporter from CLI using the command
    <npm install –g newman-reporter-htmlextra>
    

All you have to do is add the ‘-r’ flag followed by ‘htmlextra’ in the CLI command when executing a collection in Postman. Upon completion of the test run, an HTML file will be automatically generated within the Newman folder in the corresponding directory.

CLI Command:

 newman run collection name.json  --globals global variable name.json --env-var "token=YOUR_BEARER_TOKEN"  -r cli,htmlextra

newman postman report html

Benefits of API Automation Testing

Automating API tests offers numerous advantages beyond manual testing, enhancing developer workflows and facilitating rapid iteration. So the benefits we’ve discussed are not specific to Postman API automation testing as they apply to API automation on the whole.

Integration with UI Testing:

Combining UI testing with API automation addresses the frontend-backend interplay common in modern applications. This integration ensures comprehensive testing coverage, validating both the frontend and backend operations seamlessly.

Handling Data Complexity:

APIs interact with diverse data types, and API automation excels in managing this complexity effortlessly. Automated testing tools adeptly navigate through different data structures, meticulously validating inputs and outputs, irrespective of the format—be it JSON, XML, or others.

Early Issue Detection:

API automation facilitates rapid identification of problems and issues early in the development lifecycle. By automating API endpoint testing, developers streamline the debugging process, saving significant time by detecting issues before they escalate.

Integration with CI/CD Pipelines:

API automation seamlessly integrates into CI/CD pipelines, ensuring thorough testing of each code change before deployment. Automating the CI/CD process accelerates development cycles, promotes continuous delivery, and enhances the overall software release procedure.

Data-Driven Testing:

API automation enables teams to conduct data-driven testing effectively. By adjusting inputs and evaluating associated outputs, testing scenarios can be varied, ensuring consistent API performance across various circumstances.

Simulation of Realistic Scenarios:

API automation facilitates the realistic simulation of scenarios encountered in live environments. This provides valuable insights into API behavior under different loads and situations, encompassing scalability, performance, and stress testing.

Best Practices of API Test Automation

In order to achieve all the said benefits, you’ll have to follow the best practices when implementing Postman API automation testing.

Early and Continuous Testing: Initiate API testing in the development lifecycle’s early stages and sustain it throughout, facilitating prompt issue detection and mitigation, thus reducing development costs.

Diverse Test Case Design: Craft test cases encompassing a variety of input combinations to thoroughly assess API functionality, including valid and invalid inputs, edge cases, and boundary conditions.

Assertion-Based Response Verification: Employ assertions to validate API responses against expected outcomes, scrutinizing aspects such as response codes, timing, data integrity, and other critical parameters.

Effective Test Data Management: Efficiently manage test data by leveraging techniques like data-driven testing, parameterization, and data generation, ensuring comprehensive test coverage and minimizing reliance on manual data setup.

Robust Security Testing: Given the susceptibility of APIs to security breaches, prioritize security testing to evaluate authentication, authorization, encryption, input validation, and defenses against common vulnerabilities.

Performance and Scalability Monitoring: Conduct load and stress testing to assess API performance under anticipated high traffic and concurrent requests, monitoring metrics like response times, throughput, and resource utilization to identify and address performance bottlenecks.

Conclusion:

Now that we have reached the end of our tutorial, we hope you have a clear understanding of how to achieve Postman API Automation Testing. To sum it all up, Postman is a great choice as it requires minimum code to perform automation testing, supports scheduled test executions, and Newman integration for seamless reporting. We as a software testing company have found great value in using Postman and hope you will be able to as well.

Comments(0)

Submit a Comment

Your email address will not be published. Required fields are marked *

Talk to our Experts

Amazing clients who
trust us


poloatto
ABB
polaris
ooredo
stryker
mobility