top of page
HyperTest_edited.png
8 February 2024
13 Min. Read

The Most Comprehensive ‘How to use’ Postman Guide for 2024

Welcome to this comprehensive tutorial on mastering Postman, the popular API testing tool. In this guide, we delve into the core functionalities of Postman, exploring its powerful features such as Postman Tests, Data Parameterization, Collections, and Data-Driven Testing.


Whether you're a beginner stepping into the world of API development or an experienced developer seeking to enhance your testing strategies, this tutorial is designed to provide you with a deep understanding of how Postman can streamline your API testing process.


We'll walk through practical examples, including working with the JSONPlaceholder API, to demonstrate how you can leverage Postman to create efficient, robust, and reusable tests, making your API development process both effective and scalable.


We can start with absolute fundamentals by learning how to construct and test GET and POST requests with Postman. Let’s begin.



Working with requests, GET and POST


We will use https://jsonplaceholder.typicode.com/posts for our tutorial which is a fake online REST service, so it simulates the behavior of a real API but doesn't actually create or store data.


➡️GET Request in Postman

A GET request is used to retrieve data from a server. Here’s how you can make a GET request to the JSONPlaceholder API to fetch posts:


1.Open Postman: Start by opening Postman on your computer.


2. Create a New Request: Click on the “New” button or the "+" tab to open a new request tab.


3. Set the HTTP Method to GET: On the new request tab, you will see a dropdown menu next to the URL field. Select "GET" from this dropdown.


4. Enter the Request URL: In the URL field, enter the endpoint for fetching posts: https://jsonplaceholder.typicode.com/posts. This URL is the endpoint provided by JSONPlaceholder to get a list of posts.


5. Send the Request: Click the "Send" button to make the request.


6. View the Response: The response from the server will be displayed in the lower section of Postman. It should show a list of posts in JSON format.


GET Request in Postman

➡️POST Request in Postman

A POST request is used to send data to a server to create/update a resource. Here’s how to make a POST request to the JSONPlaceholder API to create a new post:


1.Create a New Request: As before, open a new request tab in Postman.


2. Set the HTTP Method to POST: Select "POST" from the dropdown menu next to the URL field.


3. Enter the Request URL: Use the same URL as the GET request: https://jsonplaceholder.typicode.com/posts.


4. Enter Request Headers: Go to the "Headers" tab in the request setup. Add a header with Key as "Content-Type" and Value as "application/json". This indicates that the body of your request is in JSON format.


POST Request in Postman

5. Enter Request Body: Switch to the "Body" tab. Select the "raw" radio button and choose "JSON" from the dropdown. Enter the JSON data for the new post.


For example:

jsonCopy code
{
  "title": "foo",
  "body": "bar",
  "userId": 1
}

6. Send the Request: Click the "Send" button.


7. View the Response: The server's response will be displayed in the lower section. For JSONPlaceholder, it will show the JSON data for the newly created post, including a new ID.


View the Response


Creating Tests using Postman


A Postman test is a set of instructions written in JavaScript that are executed after a Postman request is sent to validate various aspects of the response. These tests are used to ensure that the API behaves as expected. They can check for aspects such as the status code, response time, the structure of the response data, and the correctness of response values.


Let's use the JSONPlaceholder API (a fake online REST API) as an example to explain how to write and execute tests in Postman.


Example: Testing the JSONPlaceholder API

Suppose we're testing the /posts endpoint of the JSONPlaceholder API, which returns a list of posts.


1. Creating a Test for Checking Response Status


Goal: To ensure the request to the /posts endpoint returns a successful response.


Test Setup:


pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
Creating a Test for Checking Response Status

2. Testing Response Structure


Goal: To validate that the response is an array and each item in the array has certain properties (like userId, id, title, body).


Test Setup:

After sending the GET request, write a test to check the structure. Example script:

pm.test("Response must be an array and have required properties", function () {
    let jsonData = pm.response.json();
    pm.expect(Array.isArray(jsonData)).to.be.true;
    jsonData.forEach((item) => {
        pm.expect(item).to.have.all.keys('userId', 'id', 'title', 'body');
    });
});

Testing Response Structure

3. Checking Response Content

Goal: To verify that the response contains posts with correct data types for each field.


Test Setup:

Write a test to validate data types. Example script:

pm.test("Data types are correct", function () {
    let jsonData = pm.response.json();
    jsonData.forEach((item) => {
        pm.expect(item.userId).to.be.a('number');
        pm.expect(item.id).to.be.a('number');
        pm.expect(item.title).to.be.a('string');
        pm.expect(item.body).to.be.a('string');
    });
});

Checking Response Content

So good Postman tests need to have good assertions that check for status codes, schema and the data. These JS code blocks need to be written and updated with every minor or major change in the API to keep testing the updated reality.


We understand that’s a lot of manual work, and the fast-moving agile teams can’t keep up with their release cycles if they are stuck in this process of building test cases manually. That’s why we at HyperTest have created an approach that automatically works on building API tests and writing assertions.


The SDK version of HyperTest sits in your code and monitors the application to auto-generate high-level unit tests that test every commit. It’s record and replay mode is capable of covering every possible user scenario, eliminating the need to write and maintain test cases on your own.


  • The HyperTest SDK is positioned directly above a service or SUT, where it monitors and logs telemetry data of all incoming requests, responses of the SUT and its dependent systems.


Record Mode HyperTest
  • Covers more scenarios than humanly possible, and when replayed it verifies the SUT and its communication with all dependencies without asking teams to write a single line of test code.


Test Mode Hypertest

If you possess an abundance of time and are amenable to dedicating days to the writing and upkeep of test cases, as opposed to the mere minutes required with HyperTest, then let us proceed with the tutorial.

Data Parametrization to make Postman Tests Reusable


Request parameterisation in Postman allows you to define variables that can be used across multiple requests. This is particularly useful for testing different scenarios or for reusing similar requests with different data. We'll continue using the JSONPlaceholder API for this example.


Step-by-Step Guide for Request Parameterisation in Postman


1. Setting Up Environment Variables


1.1. Create an Environment: First, you need to create an environment in Postman. Click on the “Environments” tab on the left sidebar. Click on “New” to create a new environment. Name it something relevant, like “TestEnv”.


1.2. Add Variables: In your new environment, add variables that you want to parameterise. For example, you can create variables like baseUrl and userId. Set the initial value for baseUrl as https://jsonplaceholder.typicode.com and for userId as 1.


1.3. Select the Environment: Once you've set up your environment, select it from the dropdown at the top right corner of Postman.


Step 1: Request Parameterisation in Postman

Step4: Request Parameterisation in Postman

2. Using Variables in Requests


2.1. Create a GET Request: Let’s say you want to fetch posts of a specific user. Create a new request by clicking on the "+" tab.


2.2. Set Up the GET Request with Variables: In the URL field, use the variables by wrapping them in double curly braces. For example, enter {{baseUrl}}/posts?userId={{userId}}. This tells Postman to replace these placeholders with the corresponding variable values from the selected environment.


2.3. Send the Request: Click “Send” and observe how Postman substitutes the variables with their actual values and executes the request.


3. Changing Variable Values


  1. Edit Variables: Go back to your environment settings. Change the value of userId to another number, like 2.


  2. Resend the Request: With the environment still selected, resend the same request. Notice how the request now fetches posts for the updated user ID.


4. Using Variables in POST Request


  1. Create a POST Request: Open a new tab and set the request type to POST. For the URL, use {{baseUrl}}/posts.


  2. Setup Headers: Set the “Content-Type” header to “application/json”.


  3. Setup Body with Variables: In the request body (raw JSON format), you can also use variables. For example:


{
  "title": "A Title",
  "body": "Post body",
  "userId": {{userId}}
}

Postman can also generate random data for your requests without the need for you to prepare a dataset yourself. This is typically done using dynamic variables in Postman's scripting feature. Postman has a built-in dynamic variable feature and scripting capabilities in the Pre-request Script and Tests sections, where you can use JavaScript to generate random data.


➡️Using Built-in Dynamic Variables

Postman offers a set of dynamic variables that you can use directly in your requests. For example:


  • {{$randomInt}}: A random integer between 0 and 1000.

  • {{$guid}}: A v4 style GUID.

  • {{$timestamp}}: The current UNIX timestamp.

  • {{$randomFirstName}}: A random first name.


You can use these directly in your URL, query parameters, headers, or body. For example, if you need a random email, you could set up your JSON body like this:


{
"email": "user{{$randomInt}}@example.com",
"name": "{{$randomFirstName}}"
}

➡️Using Pre-request Scripts for Custom Random Data

For more specific random data needs, you can write JavaScript code in the Pre-request Script tab of your request. Here's an example:


javascriptCopy code
// Generate a random user ID between 1 and 100
pm.environment.set("userId", Math.floor(Math.random() * 100) + 1);

// Generate a random username
var usernames = ['userA', 'userB', 'userC', 'userD'];
pm.environment.set("userName", usernames[Math.floor(Math.random() * usernames.length)]);

Then, in your request, you can use {{userId}} and {{userName}} as variables, and they will be replaced with the values set in the script.


Creating test data for data-driven testing is widely recognized as a significant challenge by QA professionals. HyperTest's mocking capabilities entirely remove the difficulty of maintaining states for testing specific features. Let's shed some light on this:


Imagine you’re testing an e-commerce app. There’s this new feature of “loyalty points” you want to test.


But before getting to that stage, you need to prepare several pieces of test data, including:


➡️A valid user account

➡️A valid product listing

➡️Sufficient inventory for the product

➡️The addition of the product to a shopping cart


This setup is necessary before the app reaches the state where the discount via loyalty points can be applied.


The scenario described is relatively straightforward. However, an e-commerce app may contain hundreds of such flows requiring test data preparation. Managing the test data and app states for numerous scenarios significantly increases the workload and stress for QA engineers.


HyperTest has developed an approach to help quality teams test end-to-end scenarios without needing to spend any time creating and managing test data.



➡️Using Tests to Assert Random Responses

Similarly, if you want to validate the response of a request that returns random data, you can write scripts in the Tests tab. For example, to check if a returned ID is an integer:


javascriptCopy code
var jsonData = pm.response.json();
pm.test("ID is an integer", function () {
    pm.expect(Number.isInteger(jsonData.id)).to.be.true;
});

Postman Collections

A Postman Collection is a group of saved API requests that can be organized into folders. Collections are useful for grouping together related API requests, which can be for the same API or a set of APIs that serve a similar function. Collections in Postman can also contain subfolders, environments, tests, and scripts, providing a comprehensive suite for API testing and development.


1. Creating the Collection


  • Start by Creating a New Collection: In Postman, click on the “New” button, then choose “Collection”. Name the collection, for example, “JSONPlaceholder API Tests”.


  • Add Descriptions (Optional): You can add a description to your collection, which can include notes about the API, its usage, or any other relevant information.


2. Adding Requests to the Collection


  • Create Requests for Various Endpoints: Within this collection, you can create different API requests corresponding to the various endpoints of the JSONPlaceholder API. For example:


    • A GET request to /posts to retrieve all posts.

    • A POST request to /posts to create a new post.

    • A GET request to /posts/{id} to retrieve a specific post by ID.

    • A PUT request to /posts/{id} to update a specific post.

    • A DELETE request to /posts/{id} to delete a specific post.


  • Organizing with Folders: For better organization, you can create folders within the collection. For instance, separate folders for “Posts”, “Comments”, “Users”, etc., if you plan to expand testing to cover these areas.


Adding Requests to the Collection

3. Adding Tests and Scripts


  • Each request in the collection can have its own set of tests and pre-request scripts. This allows you to automate testing and set up environments dynamically. For instance, you might write tests to validate the response structure and status code for each GET request.


4. Using Environments with the Collection


  • You can create and select different environments for your collection. For example, you might have a “Testing” environment with the base URL set to the JSONPlaceholder API. This environment can then be used across all requests in the collection.


5. Sharing and Collaboration


  • Collections can be shared with team members or exported for use by other stakeholders. This is particularly useful for collaborative projects and ensures consistency across different development environments.


6. Running Collections


  • Postman also allows you to run the entire collection or specific folders within a collection. This is useful for regression testing, where you need to verify that your API behaves as expected after changes.

Interested in an approach that can automatically generate Postman collections without writing scripts?

Data Driven Testing

Now that you understand Postman collections, you’d be interested in a Postman capability that lets you test your APIs with different data sets. This helps you verify if the APIs in a test scenario behave the same way with different data without manually changing the input for each test.


Example: Data-Driven Testing with JSONPlaceholder API


Scenario: Testing User Posts Creation

Suppose you want to test the creation of posts for different users and ensure that the API correctly processes various input data. You would need to test the POST request to the /posts endpoint with different sets of user data.


Step 1: Prepare the Data File

First, you need to create a data file in JSON or CSV format. This file should contain the data sets you want to test. Here's an example JSON data file:


[
{"userId": 1, "title": "Post 1", "body": "Body of post 1"},
{"userId": 2, "title": "Post 2", "body": "Body of post 2"},
{"userId": 3, "title": "Post 3", "body": "Body of post 3"}
]

Each object in the array represents a different set of data to be used in the test.


Step 2: Create a POST Request in Postman

Create a new request in Postman to POST data to https://jsonplaceholder.typicode.com/posts.

In the request body, use variables to represent data that will be taken from your data file. For example:


{
"userId": {{userId}},
"title": "{{title}}",
"body": "{{body}}"
}

Step 3: Write Tests for Your Request

In the "Tests" tab of the request, you can write tests to validate the response for each data set. For example:


pm.test("Response has correct userId", function () {
var responseJson = pm.response.json();
pm.expect(responseJson.userId).to.eql(parseInt(pm.variables.get("userId")));
});

This test checks if the userId in the response matches the userId sent in the request.


Step 4: Running the Collection with the Data File

➡️ Save your request into a collection.

➡️ To run the collection with your data file, click on the Runner button in Postman.

➡️ Drag and drop your collection into the Runner, and then drag and drop your data file into the "Select File" area under the "Data" section.

➡️ Run the collection. Postman will execute the request once for each set of data in your data file.


Running the Collection with the Data File

Step 5: Analyze the Test Results

➡️ In the Runner, you'll see the results of each test for every iteration (each set of data from your file).

➡️ Review the results to ensure your API handles each data set as expected.



Mocking: Powerful way to simulate and test APIs


Mocking is a trick that is routinely employed by developers and testers to continue to test APIs that depend on external services or 3rd party APIs, without needing these dependencies available all the time. Say you are developer that needs to test a new feature and in order to do that successfully you call and consume the response of any external, 3rd party or internal API.


Mocking allows you to keep a dummy response of the dependency ready as when you run a collection or Postman test that runs your API. This also helps when you want to test interactions with APIs that you don't control or when you're trying to avoid costs, rate limits, or side effects of using the real API.


Example Scenario: Mocking a Weather API


Scenario Description

Suppose your application needs to fetch weather information from a third-party weather API. The actual API, let's call it RealWeatherAPI, provides weather data based on location. However, you want to mock this API for testing purposes.


Step 1: Define the API Request


  1. Identify the API Request: Determine the structure of the request you need to make. For example, a GET request to https://realweatherapi.com/data?location=London to fetch weather data for London.


Step 2: Create a Mock Request in Postman


  1. Open Postman and create a new request.

  2. Set Up the Request: Use the method and URL pattern of the RealWeatherAPI. For example, set the method to GET and URL to something like https://{{mockServer}}/data?location=London.


Step 3: Define a Sample Response


  1. Add a New Example: In the request setup, go to the "Examples" section and create a new example.

  2. Mock the Response:

    • Set the response status to 200 OK.

    • Define a mock response body that resembles what you'd expect from RealWeatherAPI. For example:


{
"location": "London",
"temperature": "15°C",
"condition": "Partly Cloudy"
}

Step 4: Create a Mock Server


  1. Navigate to the 'Mocks' Tab and create a new mock server.

  2. Configure the Mock Server:

    • Choose the request you created.

    • Give your mock server a name, like "Weather API Mock".

    • Create the mock server and copy its URL.


Step 5: Use the Mock Server


  1. Update the Request URL: Replace {{mockServer}} in your request URL with the actual mock server URL provided by Postman.

  2. Send the Request: When you send the request, you should receive the mocked response you defined earlier.


Step 6: Integrate Mock Server in Your Application


  1. Use the Mock Server URL: In your application code, replace calls to RealWeatherAPI with calls to your Postman mock server.

  2. Test Your Application: Test your application's functionality using the mock responses to ensure it handles the data correctly.



Conclusion


We conclude the article here, having focused specifically on topics that are relevant for beginner to intermediate level developers and API testers who want to consider Postman for API development, management and testing.


Postman stands out not just as a tool for making API calls, but as a complete suite for API development, testing, documentation, and collaboration. Its ability to simulate various scenarios, automate tests, and integrate seamlessly into different stages of API lifecycle management makes it an indispensable asset for developers and testers alike.


If you've reached this point and appreciate Postman's capabilities, take a look at HyperTest. It effortlessly manages tasks, automatically crafting and executing API tests, conducting data-driven testing without any data preparation, and handling advanced features like API mocking and environment management. The no-code capability of our solution has empowered teams at companies such as Nykaa, Fyers, Porter, etc., leading to a remarkable 50% reduction in testing time and a substantial 90% enhancement in code quality.



Frequently Asked Questions

1. What are the basics of Postman?

Postman is a popular tool for API testing that allows users to send requests to web servers and view responses. It supports various HTTP methods like GET, POST, and PUT. Users can add headers, parameters, and body data to requests. Postman facilitates the organization of tests into collections and offers features for automated testing, environment variables, and response validation, streamlining API development and testing workflows.

2. How to use Postman tool for API testing?

To use Postman for API testing, install Postman, create a new request, and select the HTTP method. Enter the API endpoint, add headers or parameters if needed, and input body data for methods like POST. Click "Send" to execute the request and analyze the response. Requests can be organized into collections for management. Postman also supports variables and tests for dynamic data and response validation.

3. What are the different request types supported by Postman?

Postman supports several HTTP request types, including GET (retrieve data), POST (submit data), PUT (update resources), DELETE (remove resources), PATCH (make partial updates), HEAD (retrieve headers), OPTIONS (get supported HTTP methods), and more, catering to diverse API testing needs.

For your next read

Dive deeper with these related posts!

Postman Tool for API Testing Vs HyperTest: Comparison
04 Min. Read

Postman Tool for API Testing Vs HyperTest: Comparison

Top 5 Katalon Alternatives and Competitors
11 Min. Read

Top 5 Katalon Alternatives and Competitors

FinTech Regression Testing Essentials
07 Min. Read

FinTech Regression Testing Essentials

bottom of page