How I used Postman to test my Express API
Tags: postman, postmanapi, express, backend
Published: 2023-06-18 21:16:35

In this article I will show how I used the **Postman** platform to test and develop a simple API project built in Express.

There are many resources you can find online on the subject, and I recommend you check them out for more tips (I will link a few in the References section at the end). For a systematic approach, you can start from the very own [Postman documentation](https://learning.postman.com/docs/introduction/overview/). Here I will show my personal experience using Postman, with some beginner-friendly steps - after all, this was a beginner's project as well.

---

#### Table of Contents

- [What is Postman](#what-is-postman)
- [Setting up Postman](#setting-up-postman)
- [Using Postman](#using-postman)
  - [Requests](#requests)
  - [Collections](#collections)
  - [Authorization](#authorization)
- [Conclusion](#conclusion)
- [Further reading](#further-reading)

---

## What is Postman


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxus3rxtup24nno82t19.png)

Postman is an **API platform** that developers can use to build, test and use their APIs. It provides a wide range of functionalities, and just to mention a few: creating workflows, setting up team collaboration workspaces, configuring governance and security rules, and generating reports.

There are a few different pricing plans depending on the size of your enterprise. The good news is, Postman is [free to use](https://learning.postman.com/docs/collaborating-in-postman/working-with-your-team/collaboration-overview/#:~:text=in%20this%20section.-,Postman%20Free%20lets%20teams%20of%20up%20to%20three%20work%20together,in%20the%20upper%2Dright%20corner.) for developers not working with a team, or in a team of up to three people. So, a great starting place for solo projects like mine.

---

## Setting up Postman

Go and [register](https://identity.getpostman.com/signup) a Postman account if you don't have one already. Done? Great! Now you can start using Postman.

You can launch the platform from your web browser, but bear in mind that it comes with certain limitations, like not being able to use the _Find and replace_ method to find and replace values in a workspace.

It is therefore recommended, whenever you can, to download the latest Postman version and using it directly on your machine. All the steps can be found at [this link](https://learning.postman.com/docs/getting-started/installation-and-updates/#using-the-postman-web-app).

---

## Using Postman


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vdo5l6f5k2fioxsdqq44.png)

My project consists of a collection with CRUD logic for the items, an authentication system that uses JWT tokens, and a posts and comments system. [Here](https://github.com/BiceSchembri/express-API-tattoo) you can view the Github repo.

The project was built with the **Express** framework for **Node.js**, together with a SQL database. The aim of the assignment was to build and test the back-end side only, meaning the whole user interface was missing. That is why I used Postman to process the requests to read, create, update, and delete items from my collection.

To start, I created a new **Workspace**. You can have multiple workspaces in your account, both personal or shared between team members. Then create a new Collection bu clicking on the **+** sign on your Collections tab, under your Workspace name, and give it a meaningful name.

### Collections

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n2jiaffqxzfkiu8qolsa.png)

Collections help keep your requests organized, not only for better readability but also for testing purposes. In my Postman workspace, I wanted to follow the same structure and logic as my project repository - meaning requests were divided into

- **Profile** - endpoints for the user profile / dashboard
- **Session** - register, login and logout routes
- **Products** - CRUD routes for the collection items
- **Posts** - CRUD for new posts published by users
- **Comments** - CRUD for comments under posts
- **Admin** - endpoints accessible by admins only, e.g. to delete users
- **Landing page**

### Requests

Now I could add requests to my collections.

As a refresher, these are the different HTTP requests:

| HTTP Method | Description                                              |
| ----------- | -------------------------------------------------------- |
| GET         | Retrieves a representation of a resource or resource(s). |
| POST        | Submits data to be processed to create a new resource.   |
| PUT         | Updates or replaces an existing resource.                |
| PATCH       | Partially updates an existing resource.                  |
| DELETE      | Removes a specified resource.                            |
| HEAD        | Retrieves only the response headers for a resource.      |
| OPTIONS     | Returns the HTTP methods supported by a resource.        |

And here are the steps to add them in Postman.

1. **Create a new request** by clicking on the **+** sign at the top of your workspace overview.

2. **Specify the HTTP method**. The default request is GET, but you can select the type you need from the drop-down menu.

3. **Enter the URL** in the appropriate field (in my case, the localhost path followed by the correct URI). Remember to set the appropriate request URL, including any query parameters or route parameters.

4. **Add a body** if it is a POST/PUT/PATCH request. The body is the data that is sent to the API endpoint, so you will need it if you are creating or updating a resource. DELETE generally does not require a body, nor does a GET request, since it is only retrieving data from the server. Typically, you will specify `raw` mode and select the `JSON` format for your body data, which will be written in curly brackets.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vuqlozcgrhtvhlqrqkga.png)

5. **Anything else?** You might want to specify particular headers to send along with requests (aka additional metadata). This was not the case for my project - as I said, I kept things quite simple!

6. **Hit 'Send' to test it.** Now you can pay attention to the [Response](https://learning.postman.com/docs/sending-requests/responses/) you get, the Status, the time and size. You can save the response as Example as well. Keep reading to see different responses depending on the auth privileges.

7. **Name your request and hit 'Save'** so you will be able to come back to it (you can modify any part of it later on, or keep adding new requests).

### Authorization

As mentioned above, I added some **authentication and authorization** to my project as well. I decided to implement my auth/auth using **[JWT tokens](https://jwt.io/)**.

> _**TIP!**_
Check out [this article](https://dev.to/rallofield/auth-auth-auth-2h3m) for a handy guide on **using middlewares in Express**, specifically for JWT authentication, and how to test them with Postman.
>

That meant I couldn't simply send any request via Postman and expect to receive a response - for certain routes and requests, I had to have access rights as user or admin. Only logged in users could publish posts or comments, or view and modify their own personal data; only admins could delete users, and so on.

A few steps were needed here: let's break them down.

1. First of all, I had to **obtain a valid JWT token** by sending a **login request** via Postman.

2. In the **Response** overview, under the **Headers** section, I selected and copied the token that can be seen in the `Set-Cookie` field.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sesmfbradk5osj5h9iz7.png)

3. I headed over to the [JWT.io page](https://jwt.io/) and copy-pasted the token obtained from the authentication request to decode it.

4. Now I could add some extra configuration in the **Authorization** section.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4gp1czemjx8nut5gdk5n.png)

- For **Type**, I selected `JWT Bearer`.
- For **Add JWT token to**, I selected `Request Header`.
- **Algorithm**: usually, the algorithm used to generate the JWT signature is `HS256`. It is the preselected option.
- **Secret**: This is the JWT access token that I generated and saved in my `.env` file.
- The **Header** and **Payload** that were decoded previously could also be added now.

Now see the different responses depending on the authentication.

First, a user who is not authenticated (not registered or not logged in):


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/00bhozwyw45m4dkgnuz2.png)

Then a user who is logged in, but not authorized to access a specific resource:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q66ceivgqho7kdtcj28k.png)

Finally, a user that is logged in and authorized to perform the request:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/823n04xowxsgd2rx32cw.png)

---

## Conclusion

Postman helped me to build and test my pure-backend collection project with a user-friendly interface and clear instructions. Online tutorials and guides were there to help with the trickier configuration bits.

Although I did not use all the tools that Postman offers to work on my project, what I had was enough to make my work easier to build and to test. More tools are certainly worth exploring - above all, **[automated testing](https://www.postman.com/automated-testing/)**, which I hope to implement soon in this project or the next one.

## Further reading

I hope this article helped you! It just scratched the surface. Here you can find a few more useful resources to start testing your API with Postman.

- [How to Use Postman to Test an API
  ](https://androidgeek.co/how-to-use-postman-to-test-an-api-a8eefdb1d321)
- [API Testing with Postman — Getting Started
  ](https://medium.com/assertqualityassurance/rest-api-test-automation-with-postman-jenkins-1-of-3-860edf3c2a45)
- [API Automation with Postman – Best Practices by Example
  ](https://www.zartis.com/api-automation-with-postman-best-practices-by-example/)