Blog / API Testing

Postman API testing by example

Postman is a tool to help you develop APIs. Postman helps you build APIs by providing tools to capture, validate, and test requests and responses. API testing is the process of verifying that your Application Programming Interface (API) is working correctly. This article will use Postman & Javascript for API testing.

Written byMatt
Published OnSun Aug 15 2021
Last UpdatedSun Aug 15 2021

Postman is a tool to help you develop APIs. Postman helps you build APIs by providing tools to capture, validate, and test requests and responses. API testing is the process of verifying that your Application Programming Interface (API) is working correctly. This article will use Postman & Javascript for API testing.

Table of Contents

Core concepts in Postman

Postman offers many features, though; in this article, we will talk about how to test your API. The features include making requests, Inspecting responses, embedding global and Environment variables, and writing tests in Javascript, so without further ado, let’s start with some core concepts of Postman.

Postman Workspaces

A Postman workspace is where you can organize your API and team up with others in your organization.

There are three kinds of workspaces in Postman:

  1. Personal workspace, as the name suggests, is for personal usage.
  2. Private workspace is only available to people who you invite to collaborate within the workspace. Then, you can organize it into folders and share it with your workspace members.
  3. Public Workspaces allow you to share your APIs with the world. They are searchable and accessible for free.

Postman’s API testing features are available for Personal, Private, and Public workspaces.

Postman Collection

A Postman collection consists of a group of HTTP requests. As the name suggests, collections help you organize your workspace.

Collections offer features to collaborate with the team members, generate tests for your API, run the requests automatically, authorization config, pre-request scripts, and any variables you want to share among the collection’s requests.

Request

Postman’s requests are instructions for Postman to send HTTP requests to any API. Requests are defined and configured by you using the Postman GUI.

The chances are that you don’t have an API handy to try out Postman with it. If that’s the case, you can use Rick & Morty API or HTTP Bin API. For more information about the available endpoints, please consult the documentation for each API.

Send HTTP requests with Postman

With the core concepts out of our way, let’s use Postman for sending a basic GET request.

Send a GET request with Postman

Typically, we use GET requests for retrieving data from an API. Follow the below steps to make your first request in Postman.

  1. Add a new request by hovering your mouse over your collection of choice (if you don’t have any, please create one now), click on the little ... icon, and then click on the Add request link.
  2. Pick a name that suits your request best.
  3. Since the GET method is selected by default, you don’t need to select the method.
  4. Use the URL field to set the endpoint URL
  5. Click on the Send button. Postman sends the request to the provided endpoint and shows the result.

Example HTTP Get request using Postman API client

Example HTTP Get request using Postman API client

Postman displays the API response in the Response section.

Example HTTP Get request using Postman API client

Send a POST request with Postman

Unlike GET requests, POST requests can contain a request body. Postman allows you to include data of different formats in the request body.

How to send POST requests with Form Data in Postman

  1. Create a new request
  2. Select POST HTTP method from the dropdown.
  3. Set your API endpoint in the URL field.
  4. Click on the Body tab to set the request body
  5. Click on form-data
  6. Set the field name using the KEY column.
  7. Set the field value using the VALUE column.
  8. Click on the Send button.

Example HTTP POST request using Postman API client

Send a DELETE request with Postman

In Restfuly APIs, Delete requests are responsible for deleting data. This step-by-step guide lets you send a DELETE request to a selected API endpoint.

  1. Create a new request
  2. Select the DELETE HTTP method from the dropdown.
  3. Use the Url field to set the URL endpoint
  4. Click on the Send button.

Example HTTP POST request using Postman API client

How to set query string parameters in Postman?

A query string is a string of characters added to the end of a URL in a web browser to pass information to the API. Query string could be anything from information about the user (their location, age, interests, name) to information about the endpoint they are requesting).

A typical URL with a query string looks like http://httpbin.com/?anything=test. A pair of key and value are separated using =.

We can use query string parameters with any HTTP method.

Here’s how you can add a query string parameter to your API endpoint URL in Postman:

  1. Set the query string parameter name using the KEY column.
  2. Set the query string parameter value using the VALUE column.
  3. Click on the Send button.

Example of setting query string using Postman API client


What are Variables in Postman?

Variables represent data and values in Postman. You can define a variable and reuse it by referencing it throughout your scripts and requests. Postman variables support different scopes. These scopes are:

What are the Environment Variables, and how to use them?

Environments are a group of variables that you can use in your requests. It helps you manage the team member’s access to the shared data.

Creating a new environment, follow the steps listed below.

  1. Switch to the Environments tab and click on the + button
  2. Pick a name for your environment
  3. Use the VARIABLE column to set a name for your environment variable
  4. Use the CURRENT VALUE column to set a value
  5. Once you are done, click on the Save button

Example of setting environment variables using Postman API client

Example Postman tests in Javascript

Postman uses Javascript for API testing & API monitoring. If you don’t know how to code in Javascript or prefer a no-code API testing tool, we highly recommend reading our top API testing tools article to learn more about No Code API testing tools.

Test API status code using Postman

If a user wants to interact with the API, they will send an HTTP request to the API endpoint, and depending on the action and content of the request, the server responds with the appropriate status code. We can define an HTTP response as either a success or an error depending on whether or not the request was successful.

Checking the response status code is one way to test an API. The below code snippets verify the HTTP response status code in Postman.

The table below lists pm fields with information related to the response status code:

FieldDescriptionExample
pm.response.statusStatus TextOK
pm.response.codeStatus Code200

Postman test to check whether status is 200 OK

pm.test("the endpoint returns the expected status code", () => {
  // change 200 to the response code you expect
  const expectedStatusCode = 200;

  pm.response.to.have.status(expectedStatusCode);
});

Postman test to check whether status is 200 or 201

pm.test("the endpoint returns the expected status code", () => {
  // comma separate the valid response codes below
  const expectedStatusCodes = [200, 201];

  pm.expect(pm.response.code).to.be.oneOf(
    expectedStatusCodes,
    `expected response status to be one of ${expectedStatusCodes} but got ${pm.response.code}.`,
  );
});

Postman test to check status code is not 404

pm.test("the endpoint does not return unexpected status code", () => {
  // change 404 to the response code you do not expect
  const expectedStatusCode = 404;

  pm.response.to.not.have.status(expectedStatusCode);
});

Postman test to check status is not 404 or 500

pm.test("the endpoint does not return unexpected status codes", () => {
  // comma separate the valid response codes below
  const unexpectedStatusCodes = [404, 500];

  pm.expect(pm.response.code).to.not.be.oneOf(
    unexpectedStatusCodes,
    `did not expect response status to be one of ${unexpectedStatusCodes} but got ${pm.response.code}.`,
  );
});

Test API response time using Postman

The API response time is an important metric to test, measuring how long it takes for the API to respond to requests. Slow response times can lead to poor user experience and be severely affected by peak traffic conditions. This section shows you how to test response time in Postman.

The table below lists pm fields with information related to response time:

FieldDescriptionExample
pm.response.responseTimeResponse time (in milliseconds)255

Postman test to check response time

pm.test("API responds within the expected treshhold", () => {
  // set the response time in milliseconds
  const expectedTimeInMilliseconds = 500;

  pm.expect(pm.response.responseTime).to.be.lessThan(
    expectedTimeInMilliseconds + 1,
    `The endpoint did not respond within ${expectedTimeInMilliseconds} ms. Response came in ${pm.response.responseTime} ms`,
  );
});

Test API response body using Postman

API response has a body, which is the operation’s return value. The response body is returned in a JSON- or XML-encoded string. The response body defines the structure and content of the response payload.

The table below lists pm fields and functions with information related to the response body:

Field / FunctionDescriptionExample
pm.response.json()Response body (Javascript object){"hello": "world"}
pm.response.bodyResponse body (text){"hello": "world"}

Postman test to check field value in response

We can validate the value of both id and name fields of the https://rickandmortyapi.com/api/character/2 using the test below.

pm.test("API response contains the expected fields", () => {
  const response = pm.response.json();

  // the line below checks value of the id field is 2 (number).
  pm.expect(response).to.have.property("id", 2);

  // the line below checks value of the name field is Morty Smith (string).
  pm.expect(response).to.have.property("name", "Morty Smith");
});

Postman test to check nested field value in response

The script below step works for fields at the root of the response. What if we wanted to test the name field under the origin field. We can tweak the script to support fields at any level.

pm.test("API response contains the expected fields", () => {
  const response = pm.response.json();

  // the line below checks value of the id field is 2 (number).
  pm.expect(response).to.have.nested.property("id", 2);

  // the line below checks value of the name field is Morty Smith (string).
  pm.expect(response).to.have.nested.property("name", "Morty Smith");

  // the line below checks value of the origin.name field is Earth (C-137) (string).
  pm.expect(response).to.have.nested.property("origin.name", "Earth (C-137)");
});

To check value of nested fields, provide the path (from root) to the field by chaining field names using dot (.)

Postman test to check nested array value in response

We can take it even further and use the same technique to validate the value of items in the array. For example, we can use the below script to check the value of the second item in the episode array of the https://rickandmortyapi.com/api/character/2 endpoint.

pm.test("API response contains the expected fields", () => {
  const response = pm.response.json();

  // the line below checks the value of the origin.name field is Earth (C-137) (string).
  pm.expect(response).to.have.nested.property("episode.1", "https://rickandmortyapi.com/api/episode/2");
});

You may have noticed, but to access the second item in the episode list, we used the number 1; why? In Javascript, the position of the items in lists (array) starts from 0, so the first item has 0 as the position number, the second one 1, and so on.

Test API response headers using Postman

When you hit an API endpoint, one or more HTTP header is returned, along with the data from the call. This header contains information about the API endpoint that was called and can be used by API clients to understand better the call that was made.

The table below lists pm fields and functions with information related to response headers:

FieldDescription
pm.response.headersResponse heaaders

Postman test to check response header

pm.test("API response contians the expected header", () => {
  pm.response.to.have.header("Content-Type", "application/json; charset=utf-8");
});

Use Postman Dynamic Variables to generate random data

Including random data in the request is an excellent technique for API testing. In particular, including random data proves that the API is not biassed towards one particular form of data.

Dynamic Variables is a Postman API Testing feature you can leverage to include randomly generated fake data of different types in the request payload. Postman takes care of generating fake values on the request time. Dynamic Variables support ID, Email, Postal Code, and many more data shapes.

Include a Postman dynamic variable by typing {{$ in the request body field and then pick one of the available options.

Below is a list of variables you can use with Postman. Please check the Dynamic Variables article on the Postman website for a complete list.

Dynamic Variable NamePurposeExample
{{$guid}}Produces a UUID V4 on the fly611c2e81-2ccb-42d8-9ddc-2d0bfa65c1b4
{{$randomBankAccountName}}generates a random bank account namePersonal Loan
{{$isoTimestamp}}The current ISO timestamp at zero UTC2020-06-09T21:10:36.177Z
{{$randomInt}}A random integer between 0 and 1000123
{{$randomFirstName}}A random first nameDavid
{{$randomPhoneNumber}}A random 10-digit phone number562-203-1827

The screenshot below demonstrates how to send a POST request that includes randomly generated fake data for ID and bank account name.

Include Dynamic Variables in Postman requests for generating random data

Since you’re interested in this feature, we highly recommend reading our article about fuzz testing. It is a type of automated software testing, a method of discovering bugs in software by providing random input to the software under the test and monitoring any crashes and failed assertions.

No code API testing using Testfully

Testfully offers a generous free plan

Testfully is a leading No Code API testing & monitoring tool and a great Postman alternative for API testing. The below video is a quick demo of Testfully and how you can use it to test your APIs without writing code.

Testfully is a bootstrapped startup from Sydney, Australia.
We're funded by our supportive & amazing customers.

The word `testfully` is a registered trademark of Testfully Pty Ltd.