Postman API testing by example

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.


Table of Contents



Looking for a Postman alternative?

Testfully's free plan offers Unlimited team members, Multi-step tests, team collaboration, historical test results and many more features. Import from Postman supported!

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:

  • Global: these variables are accessible across your workspace.
  • Collection: these variables are accessible in collection requests and independent of any environment.
  • Environment: these variables are only accessible when their corresponding environment is selected.
  • Data: it can be imported from outside sources, for example, from a JSON file.
  • Local: as its name indicates, they are temporary and only accessible in your request or script.


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:

Field Description Example
pm.response.status Status Text OK
pm.response.code Status Code 200


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:

Field Description Example
pm.response.responseTime Response 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 / Function Description Example
pm.response.json() Response body (Javascript object) {"hello": "world"}
pm.response.body Response 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:

Field Description
pm.response.headers Response 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 Name Purpose Example
{{$guid}} Produces a UUID V4 on the fly 611c2e81-2ccb-42d8-9ddc-2d0bfa65c1b4
{{$randomBankAccountName}} generates a random bank account name Personal Loan
{{$isoTimestamp}} The current ISO timestamp at zero UTC 2020-06-09T21:10:36.177Z
{{$randomInt}} A random integer between 0 and 1000 123
{{$randomFirstName}} A random first name David
{{$randomPhoneNumber}} A random 10-digit phone number 562-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.

Recent Articles

blog-image
Top 7 Free & Paid mock API tools (2022 Review)

Sometimes called a fake API, A Mock API is when you build an API that returns the desired data. Still, it is not your actual API, and it all has been simulated for some use cases. This article covers best free & paid mock API tools in the market.




blog-image
Top 10 GraphQL clients

GraphQL is one of the hottest topics in the API development world, and that’s for good reasons: GraphQL APIs address many of the issues that we had with Restful and SOAP APIs. This article goes through the Top 10 GraphQL clients you can use today to develop and use GraphQL API.




blog-image
Why your Website is giving an HTTP 405 Method Not Allowed message and how to fix it

When a response has the status code 405, the client attempted to access a resource using an HTTP method that is not permitted by the server for that resource. Websites, Restful APIs, and web applications tend to return this error. This article provides a more detailed explanation of this status code’s meaning and how to handle it in your applications.