Introduction

Postman is a popular tool for testing APIs (Application Programming Interfaces) by sending requests to web services and analyzing their responses. It is widely used by developers and testers to streamline API development, debugging, and validation. Apart from API testing, Postman can also be used for API documentation, collaboration, and monitoring.

In this article, we are going to explore automated API testing using Postman. By following the steps outlined, you will be able to set up a collection, create API requests, and automate tests to ensure your APIs function as expected.

Prerequisites

Before you start with API testing in Postman, ensure you have the following:

  1. Postman Installed: Download and install Postman from Postman’s official website.
  2. Basic Understanding of APIs: Familiarity with API concepts such as HTTP methods (GET, POST, PUT, DELETE), request headers, and response codes.
  3. API Endpoint Access: Obtain the necessary API endpoints and credentials (if required).
  4. Postman Account (Optional): While Postman can be used without an account, signing in allows you to sync collections and use cloud-based monitoring features.

Steps to Get Started

Create a Collection

  1. Open Postman and navigate to the Collections tab.
  2. Click New Collection and give it a meaningful name.
  3. Add a description (optional) to explain the purpose of the collection.
  4. Click Create to save the collection.

Create a Request

  1. Select the HTTP method (e.g., GET, POST, PUT, DELETE).
  2. Enter the API endpoint (URL) in the request field.
  3. Save the request inside the newly created collection.

Set Request Details

  1. Add Parameters: Include query parameters (e.g., ?id=123).
  2. Add Headers: Specify headers like Content-Type: application/json or Authorization.
  3. Add Body: Use raw JSON, form-data, or other formats to send data with requests (for POST/PUT).

Send the Request

  1. Click Send and observe the response.

Validate the Response

  1. Check Status Codes (e.g., 200 for success, 404 for not found).
  2. Review Response Time to ensure performance standards.
  3. Validate the Response Body for correct data and structure.
Video outlining the basic steps

Types of Testing You Can Perform with Postman

  1. Functional Testing: Verify that each API endpoint works as intended.
  2. Integration Testing: Check if different services or APIs work together smoothly.
  3. Performance Testing: Monitor response times to ensure APIs perform under load.
  4. Security Testing: Send unauthorized or incorrect requests to test for vulnerabilities.
  5. Regression Testing: Ensure that changes to the API do not break existing functionality.

Automating Tests with Postman Scripts

Postman supports JavaScript-based test scripts, which can be written under the Scripts tab (in current versions) or the Tests tab (in previous versions).

Pre-request and Post-response Scripts

Pre-request Scripts

The Pre-request tab allows you to execute scripts before sending an API request. It is commonly used for test setup tasks such as:

  • Generating authentication tokens.
  • Setting request headers dynamically.
  • Preparing test data or variables.

Post-response Scripts

The Post-response tab (previously called the Tests tab) lets you write scripts that run after the API response is received. These scripts are used for:

  • Validating response status codes and data.
  • Extracting values and storing them as variables.
  • Automating workflows by chaining requests.

You can write scripts to automate response validation. These scripts can check for response codes, validate response data, extract dynamic values, and even chain requests together.

Variables in Postman

Postman allows you to use variables to store dynamic values, making your API testing more flexible and reusable.

Types of Variables

  1. Environment Variables
    • Scoped to a specific environment (e.g., development, staging, production).
    • Useful for storing API base URLs, authentication tokens, or configuration values.
    • Example:
      • pm.environment.set("base_url", "https://api.staging.example.com");
    • Retrieve it using:
      • pm.environment.get("base_url");
  2. Collection Variables
    • Available across all requests within a collection.
    • Useful for storing shared data such as authentication tokens.
    • Example:
      • pm.collectionVariables.set("auth_token", "your_token_value");
    • Retrieve it using:
      • pm.collectionVariables.get("auth_token");
  3. Global Variables
    • Available across all collections and requests in Postman.
    • Less commonly used but helpful for widely shared values.
    • Example:
      • pm.globals.set("global_variable", "some_value");
    • Retrieve it using:
      • pm.globals.get("global_variable");

Using Variables in Requests

Once a variable is set, you can use it in API requests like this:

  • {{base_url}}/users → Expands to the value stored in the base_url variable.
  • Headers: Authorization: Bearer {{auth_token}} → Uses the stored authentication token dynamically.

By leveraging variables, you can create dynamic, reusable test setups that simplify API testing across different environments

Writing Test Scripts

Test scripts in Postman execute after the response is received and can be used for validation, extracting values, and setting variables dynamically.

Test Format in Postman

Postman test scripts are written in JavaScript and follow a structured format using pm.test(). Inside the test function, assertions are typically made using pm.expect(), which is based on the Chai assertion library.

Basic Test Structure

pm.test("Test description", function () {
    pm.expect(actualValue).to.assertion(expectedValue);
});

Example Test Scripts

  1. Check Status Code

2. Validate Response Time

3. Check for Specific Data in the Response Body

Using Collections for Testing

Organizing Requests

  • Group Requests: Create a collection (e.g., all user-related endpoints).
  • Use Environment Variables: Store dynamic data (like URLs, API keys) to switch between environments (e.g., dev, staging, production).
  • Collection Variables: Store dynamic data within the collection, such as authentication tokens and base URLs to switch between environments.
  • Collection Runner: Execute multiple requests in a sequence to test workflows or chains of APIs.

Automating Variable Storage

If an API requires a token, you can store the token from the authentication API in a collection variable and reuse it across requests, streamlining automation, as shown in the image. This is usually done in the Post-scripts.

Postman Monitor and Newman

Automating an organized collection in Postman can be efficiently achieved using Postman Monitors and Newman.

Postman Monitors allow you to schedule and run API tests in the cloud at set intervals, making it ideal for continuous monitoring of API health and performance.

Daily run monitor results

Newman, Postman’s command-line runner, enables automation by running collections locally or in CI/CD pipelines. By integrating these tools, teams can streamline API testing, ensure reliability, and get real-time insights into failures, enhancing overall workflow efficiency.

Best Practices for API Testing Using Postman

  1. Modular Testing: Test small units before combining them into complex workflows.
  2. Error Handling: Test for both valid and invalid inputs to check API robustness.
  3. Documentation: Document test cases within Postman to ensure easy handover and collaboration.
  4. Performance Bench marking: Monitor response times across environments and endpoints.

Conclusion

Effective API integration testing is crucial for ensuring seamless communication between services, and maintaining a reliable user experience. Thorough testing helps identify issues early, improves security, and ensures APIs perform optimally under different conditions. By leveraging tools like Postman, teams can automate and streamline the testing process, reducing errors and enhancing software quality. Well-tested APIs lead to smoother integrations, better scalability, and a more robust application ecosystem.