DEV Community

Cover image for Postman for busy developers
Bilal Haidar for This Dot

Posted on • Updated on

Postman for busy developers

Documenting, testing and debugging APIs is one of, if not, the most frustrating aspect of developing REST APIs. Postman's ability to do this saves time, ensures accuracy and is hassle free.

Postman is a cross-platform tool that you install as a standalone desktop app on your Windows, Linux or MacOS computer.

Besides the additional features it provides, you can think of Postman as a "browser on steroids". It performs like a browser in sending HTTP Requests and receiving HTTP Responses. For instance, in Postman you can edit the HTTP Request Headers before sending a request to the backend. You can also apply tests on the HTTP response received from the backend.

In addition, Postman focuses on organizing your work by introducing concepts like:

  • Workspace

  • Environment

  • Collection

  • Folder

  • Variables

  • Request

  • Response

This is not everything that Postman can do. Furthermore, you can generate API Documentation by using Postman.

In this article I will tackle each of the topics listed above in more detail. In addition, I will be using Reqres a free online hosted REST-API service ready to accept requests for testing purposes.

Let's start!

Install Postman

I've been using Postman for several years now as a Chrome browser extension. However, recently this version of Postman has been retired and instead, I use the Postman standalone desktop application.

Make sure you install the app from the Postman official website.

The first time you open Postman it looks like this:

This is a quick-access menu to choose an action like creating a new Request, Collection, etc.

Postman Workspace

By default when you install and open Postman for the first time, the tool creates a default My Workspace for you.

You can manage workspaces by adding more to your system.

With a workspace, you can manage, group and organize your collections and environments. More on this shortly.

Postman offers two types of workspaces:

  • Personal

  • Team

The Personal workspace, as its name implies, is a local workspace you use on your machine. While the Team workspace is used to collaborate with others.

For this article, I will use the default My Workspace as is.

You can list your workspaces and even create new ones if needed.

You can consult the Postman official documentation on Workspaces.

Postman Environment

An environment in Postman is similar to the environments we deal with when developing apps.

For instance, when developing an app, usually you establish a minimum of three different environments. A dev or local environment, staging environment and a production environment.

For each environment you will manage a set of environment variables that are scoped to a single environment. You could store the database connection string in an environment variable. This way, you won’t need to change your code when you move your app to a different environment.

Let's take an example. I am developing my Node.js app locally and storing all my environment variables inside a .env file. Now, I deploy my app to Heroku, for example, under the staging environment. I just need to define the same environmental variables I use inside .env file under this new environment. Same thing applies when I move to the production environment. I just need to define a new set of environmental variables.

Your app remains clean and usable under all environments.

In Postman, an environment is defined as:

  • A set of key-value pairs to control a specific environment

  • A collection in Postman runs under a specific environment

You could store as environment variables the API Endpoint Base Url for instance and many other things.

To view all environments in Postman:

Currently I don't have an environment. Let's create a new one by locating and clicking on Add link.

The name environment has a name of prod. As well, I've defined an environment variable url with an initial value of https://reqres.in/. This variable is used as a base url for the REST API under test.

Once done, locate and click on Add to create the new environment with variables.

Now you can manage this environment and create other ones too.

A Postman environment needs to be selected when running a collection of requests or even a single request. As you will see shortly, I will embed the url environment variable in a request Url. Based on the environment selected, the value of url will be replaced.

For instance, under prod environment, the url will be replaced by https://reqres.in/. If running the same request under another environment, the value of url will be whatever is defined inside that environment.

Using environments and variables keep your code clean, configurable and well maintained.

Let's move on and discuss variables in Postman.

Postman Variables

A variable in Postman is similar to the concept of variables in programming languages. It's a memory placeholder to store information and retrieve later when needed.

As you've seen, we define the url variable on the environment level. Postman allows you to define variables at different levels as follows:

  • Global

  • Environment

  • Collection

  • Folder

A variable defined at the Global level applies to all requests irrespective of the environment, collection or folder selected. Of course, you could override a global variable in the levels below.

A variable defined on the Environment level applies to all requests inside collections and folders.

A variable defined on the and Collection level applies to all requests inside a specific collection and all of its folders.

Finally, a variable defined on a Folder level applies to all requests inside a specific folder.

Locate the Environment quick look icon and click it:

Locate and click Edit link under Globals section:

On this screen you can define your global variables similar to what we did at the Environment level.

You can consult the Postman official documentation on Environments and Globals.

Postman Collection

A collection in Postman is a group of API Requests that are logically related. Inside collections you can further group by a Folder.

For instance, I would create a new collection for a new app. For each Controller or API Endpoint I would create a Folder to group all requests for this endpoint in one folder. Your collection will be a collection of folders for each controller or endpoint in your app.

Locate the Collections tab and click it. You can then click on Create a collection link to open the Create a new collection form.

You start by giving the new collection a name and description.

The Description field supports Markdown.

The Authorization tab is used to define the authorization method to add to the Request Header of all requests under this collection:

In this scenario, I've selected the Bearer Token and pasted the token value itself. Now with every request you execute under this collection, an Authorization header is attached to the Request header before execution.

For this article, I will select No Auth instead.

The Pre-request Scripts and Tests tabs are used to write JavaScript code. We will come back to these tabs shortly.

Finally, you can define variables on the collection level by going to the Variables tab.

Once done, hit the Create button to create this new empty collection.

Share Collection

Now that the collection is created you can share this collection with others by clicking the Share button.

Go to the Get link and click on it:

Copy the URL showing and from any other computer, you can run the collection via this Url.

To do so, you need to install the newman NPM package by running this command:

npm install -g newman

newman package is a CLI companion for Postman. You can read more about it on newman npm page

To run the collection Url you type the following command:

newman run https://www.getpostman.com/collections/916f931e5ff24cf0d619

This command runs all the requests under this collection and gives you stats on all requests.

Add Requests

Let's add a few requests to this collection before running it. Right-click the collection name and from the context-menu select Add Request.

In this request, I will GET all users stored in the database. Click on the Save to Reqres API button to actually save the request in the collection.

Click on the List Users request under the Reqres API collection and fill in the details as shown above.

  • Environment: I've selected the prod environment

  • Method: I've selected the GET method

  • Url: I've embedded an environment variable {{ url }} by embracing the variable name with a double opening and closing curly braces. In addition, I am requesting the users endpoint passing to it a query string page of value 1.

The endpoint I've selected contains a query string. As you can see, Postman detected the query string in the Url and it automatically added a new record under Query Params table.

The rest of the tabs are used as follows:

Authorization

Authorization tab is used to add an authorization method on this request. If you have already selected one at the collection level, then you can simply inherit it here or even use another one.

Headers

You can attach additional Request Headers to this request.

For instance, I've added the Content-Type header and assigned it a value of application/json.

Body

You can use the Body tab to define the request payload. I will show you in a while how you can pass a request payload when using POST requests. Notice that you have a variety of options to select from ranging from none to form-data to raw and others?

Finally, the Pre-request Script and Tests tabs are used to write JavaScript code.

Let's hit on Save button first and then click on Send to execute the request.

A request is executed and the response is displayed in a new section beneath the request details.

The body of the response has multiple views:

  • Pretty

  • Raw

  • Preview

  • Data (JSON, XML, etc.)

The response you see above is using the Pretty mode with JSON to display the data.

You can also view the Cookies, Headers and Test Results of the response. In addition, you can view the Status of this response, the Time it took to receive a response and finally the Size of the response payload.

Finally, you can save the response.

The Test Results are directly related to the Tests tab mentioned above. You will learn more about Tests shortly.

You see how simple it is to create a new request?

I will add another GET request offline to get a single user.

Also, I will add a new POST request to create a new user by passing a user object in the body of the POST request:

Run Collection

Now that we have a total of three requests, let's run the collection.

Locate and click the Reqres API collection, click the arrow icon, located at the top-right corner, to open the collection actions.

Locate and click the Run button to execute all the requests

On the left-side panel you see:

  • All requests under the collection.

  • The environment to use, in this case the prod environment is selected.

  • The number of iterations to run the requests. The default value is 1.

  • The delay in milliseconds to simulate a certain delay in receiving the response from the backend API.

  • The Data field allows you to load variables data from a file stored on your machine. We are not using this technique for now.

On the right-side panel you can rearrange the requests to change their order of execution.

Finally, let's hit on Run Reqres API to execute the requests:

All of the requests have successfully executed. For each request you can see the Status, Size and Time.

You can then export the results to review them later.

Collections are really useful and play a major role in API regression testing. Now at any moment of time, you can introduce changes to your backend API and then run the entire collection to verify the results.

Combined with an Environment in Postman, you can run your tests not only against your local development, but also against your production or staging environments.

You can see and appreciate the time you can save with Postman in testing all these environments.

You can consult the Postman official documentation on Collections.

Postman Scripts

I mentioned Postman scripts in the beginning of this article and now it's time to delve into them.

Postman offers two types of scripts:

  • Pre-request Scripts

  • Tests

Pre-request Scripts

This script can be applied to:

  • Collection

  • Folder

  • Request

If you have scripts defined on all levels, they will run in this same order.

A Pre-request Script is a JavaScript code that runs prior to executing a request. Think of it as an Interceptor that runs before sending out the request. You use it to debug variables in a request, to make sure the variables have their correct values. Also, you can use this script to add custom request headers to a currently executing request.

Let's open the Pre-request Script tab for an existing request in Postman:

Notice on the right-side panel there is a list of links that you click and inject some scripts inside the Pre-request Script tab.

To retrieve an environment variable:

pm.environment.get("variable_key");

To retrieve a global variable:

pm.globals.get("variable_key");

To retrieve a variable defined on either Collection or Folder:

pm.variables.get("variable_key");

These scripts are using the pm object that encapsulates all API calls on Postman SDK API. You can read more about pm object.

To print a variable to console simply use the famous console.log(pm.environment.get("variable_key"));.

Let's print the url environment variable prior to executing a request by placing this line of code inside the Pre-request Script:

console.log(URL Environment Variable: ${pm.environment.get("url")});

Open the Postman Console by locating it inside the View menu. Then, execute the request:

Notice the script and the results on the Postman Console app.

You may use Postman Console to debug requests and responses.

Tests

The Tests tab allows you to write JavaScript code to execute after the request finishes executing and the response is received.

This script can be applied to:

  • Collection

  • Folder

  • Request

If you have scripts defined on all levels, they will run in this same order.

Think of a Tests script as an Interceptor that runs after the response is received. You use it to apply tests on the response received. For instance, you can test the Status Code of a response, the data received in the response, the headers received on the response, the response time is greater or less than a certain value and many other scenarios.

Let's add a test script to verify that the User object requested via /api/users/2 has a User ID of value 2.

The script used in this request:


pm.test("User ID is eqqual 2", function() {

    var jsonData = pm.response.json();

    pm.expect(jsonData.data.id).to.eql(2);

});
Enter fullscreen mode Exit fullscreen mode

The script accesses the response body and then asserts to make sure the User ID equals 2.

  • jsonData is the actual response in JSON format.

  • data is the root property of the response returned from the backend API

In the response section under the Test Results tab, Postman notifies you of the status of the test. In this case, our test runs successfully and verifies that the User ID received has a value of 2.

If the test fails you will see another message with FAIL.

Not only can you execute requests against your REST API but also write tests to verify the results.

You can completely rely on Postman to test your REST APIs from now on!

You can consult the Postman official documentation on Tests.

Conclusion

Today we touched on the very tip of the Postman iceberg! There are many more details and advanced features to cover but definitely more than can fit in one article.

Generate Documentation

Monitors

Mock Servers

However what you've seen today covers 90% of what you need from Postman to debug, document and test your REST APIs.

You can always refer back to the Postman official documentation website. They provide up to date documentation and cover every single detail in Postman.

This post was written by Bilal Haidar, a mentor with This Dot.

You can follow him on Twitter at @bhaidar.

Need JavaScript consulting, mentoring, or training help? Check out our list of services at This Dot Labs.

Top comments (0)