How to use Postman for API testing
Tags: node, testing, javascript, programming
Published: 2023-03-25 11:27:56

Testing web applications is essential to check if the code written meet the criteria and standard before deployment before it reaches the user. During the software development lifecycle of a product, it is essential to find minor and significant issues with the app, like identifying bugs within the code and fixing them promptly with the help of professionals like quality and assurance (QA) testers.

Postman is a collaborative API platform developers use to test, monitor, design, and build their APIs with a user interface (UI). According to [businesswire](https://www.businesswire.com/news/home/20220414005114/en/Postman-API-Platform-Surpasses-20-Million-Users-Driven-by-Vision-for-API-First-World), more than 20 million developers and 500,000 organizations use Postman, which only shows its success as a reliable platform for API testing.

In this article, you will learn and explore the various uses of Postman and how it can help you become productive as a developer, no matter your stack.

Let’s get started.

## What is an API?

Application programming interface (APIs) are everywhere, and it is the bedrock for how applications communicate with one another; they enable integration and automation using a set of defined protocols, HTTPS from the sending a request and receiving a response through a network.


![api credits to Ruby Roméu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p7ef8v9cvoed4xc3r94s.png)

## GitHub

The complete source code for this project is in [this repo](https://github.com/Terieyenike/create-apis-with-node).

## Prerequisites

The following are required to complete this tutorial:
- Download the [Postman app](https://www.postman.com/downloads/)
- Basic knowledge of Node.js
- [Node.js installed](https://nodejs.org/en) on your local machine. It is required for dependency installation using `npm`

## Building an API with Express.js

Express is an unopinionated web framework built on top of Node.js, the JavaScript runtime environment. Using Express to create APIs is fast.

Open your terminal and run this command to create a new directory:

```bash
mkdir api-testing
```

Next, navigate to the directory and initialize the directory with the following command:

```bash
cd api-testing

npm init -y
```

This command accepts all the defaults with the **-y** flag, which creates a package.json file.

With the package.json file created, install these dependencies:

```
npm install express
```

`express`: is used to create a server


The other package to install is **nodemon** which would be a `devDependencies`. That means it is only required to run during local development and testing.

```bash
npm install nodemon -D
```

**Configure the package.json file**

Change the values in the scripts section of the file with the following:


```js
{
 ...
 "scripts": {
   "test": "jest",
   "start": "node server.js",
   "start:dev": "nodemon server.js"
 },
 …
}
```

The script, `nodemon server.js`, will automatically restart the node application when the file notices changes.

**Note**: This program would not run without APIs in the `index.js` file.

For this project, we will use the model, view, controller (MVC) architecture pattern by dividing the application logic into three parts: the Model, View, and Controller.

Let’s create the server.

**Building the model**

Create a new directory in the project's root called **models**, and within this folder, create a new file named `friends.model.js`.

Copy and paste the code below to create the model for our API:

```js
const friends = [];

module.exports = friends;
```

This model contains an empty array with the declared variable, **friends** and exported variable.


**Building the controller**

For the controller, with the same process as the model, create a directory named **controllers** in the project’s root and within the folder, a new file, `friends.controller.js`.

Copy-paste the code below:

```js
const model = require('../models/friends.model');

function getFriends(req, res) {
  res.json(model);
}

function getOneFriend(req, res) {
  const friendId = Number(req.params.friendId);
  const friend = model[friendId];

  if (!friend) {
    res.status(404).json({ error: 'Friend does not exist' });
  } else {
    res.status(200).json(friend);
  }
}

function postNewFriend(req, res) {
  if (!req.body.name) {
    return res.status(400).json({
      error: 'Missing friend name',
    });
  }
  const newFriend = {
    name: req.body.name,
    id: model.length,
  };

  model.push(newFriend);

  res.json(newFriend);
}

module.exports = {
  getFriends,
  getOneFriend,
  postNewFriend,
};
```

The code snippet above does the following:

- Import the model 

- For the `getFriends()`, this returns the list of friends in json format 
- The `getOneFriend()`, will return just one friend in the array using the **id** identifier, and if the id does not exist, it displays a client error, 404
- The `postNewFriend()` uses the post-request method to send the data to the server
- As usual, export the three functions with `module.exports`


**Building the route**

The API endpoint in this section will communicate with each controller using its corresponding HTTP request.

Create a folder called **routes** with a new file, `friends.router.js`, with each router attached to the endpoint.

Copy and paste this code:

```js
const express = require('express');

const friendsController = require('../controllers/friends.controller');

const friendsRouter = express.Router();

friendsRouter.get('/', friendsController.getFriends);
friendsRouter.get('/:friendId', friendsController.getOneFriend);
friendsRouter.post('/', friendsController.postNewFriend);

module.exports = friendsRouter;
```

The code above does this:

- shows how to create a new router object using the `Router()` function
- Import the `friendsController` and use them in the `friendsRouter` to handle the request
- Export the `friendsRouter`

**Connecting it all**

The most important of creating or building an API server is to connect the workflow so that the MVC pattern functions to test individual endpoints.

First, create the entry point file, `app.js`, in the root directory and paste this code.

```js
const express = require('express');
const app = express();

const friendsRouter = require('./routes/friends.router');

app.use((req, res, next) => {
  const start = Date.now();
  next();
  const delta = Date.now() - start;
  console.log(`${req.method} ${req.baseUrl}${req.url} ${delta}ms`);
});

app.get('/', (req, res) => {
  res.send('welcome to the friends data response');
});

app.use(express.json());
app.use('/friends', friendsRouter);

module.exports = app;
```

The highlights for the code above does the following:

- The express module is declared
- Run the `express()` function, as this defines the instance of the app
- The middleware, `app.use()` parses the incoming JSON requests. The other middleware with endpoint, `/friends`, is the route attached to the hostname of the app
- The `GET` request with the endpoint **/** displays the message in the `res.send()` method in the browser at `http://localhost:4000`
- Export the app in the `module.exports` class

Next, create the `server.js` file in the root directory with this code:

```js
const http = require('http');
const app = require('./app');

const server = http.createServer(app);

const PORT = 4000;

server.listen(PORT, () => {
  console.log(`Server listening on port:${PORT}`);
});
```

The code above with the `listen()` function listen to the connections on the specified port and host.

Let’s now run the server with the command:

```
npm run start:dev
```

Checking the console of your terminal, it should read “Server listening on port:4000”.

## Using Postman to test the server

**Creating Postman collections**

Before creating collections for your requests, you need to create a workspace.

Click the **Workspaces** dropdown and select **Create Workspace**.


![create workspaces](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ab6dc6b0rwhc3idfjgaa.png)

Give your workspace a name and set the visibility to **Public**. After that, click **Create Workspace**.

Let’s create a new Collection in our workspace to store the requests. At the left pane of the Postman window, click the plus (“+”) icon or Create Collection.


![add collection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99nzhcpbzqgzzb1dz4w4.png)

Next, give the Collection a name.

**Adding Requests to Collections**

To create our first request, click either the Add a request inside your new collection or the three dots icon on your Collection.



![add request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kzg0n5iniejbtty7qjyu.png)

Next, name your request “post friends”. Set the request method to POST and the request URL to `http://localhost:4000/friends`, which will send data to the server to create a friend. Remember to hit Save.

Click the **Body** tab of the request, select data type **raw > JSON**, and send the request by clicking the Send button.

Enter a name as shown below:


![post friends](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9tbqt28sv57lo67qh0q.png)

To confirm the request with the GET request method, add a request named `get friends` with the path URL `http://localhost:4000/friends` which will display the friends' array in the response field as shown:



![get friend request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jpq9heku57rgscseucqy.png)


**Get an individual friend**
Add a request “get a friend” to see the output of just one friend specifying the index included in the path URL, `http:://localhost:4000/friends/0`, with a **GET** request method.

The result of this should look like this:


![single friend](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g3uti0dex31i51us23y7.png)


## Creating documentation for test APIs

It is essential to document your API workflow, like how developers create a `README.md` file for every GitHub project they start. Similarly, it is possible to do the same in Postman.

At the right pane of the app, Select the `Documentation` icon.


![create documentation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/anp6x2ok12xl4jzw2j10.png)


Once opened, you can write a detailed request description of each endpoint in your collection by clicking the pencil icon to begin.


![add request description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kxlr7qkc65j48rr6l04d.png)



## Conclusion

This article taught you the basics of using Postman to test your APIs by sending requests over the network and receiving responses through the status code, indicating either success or failed error status code.
Try Postman today and learn from its resources. If you found this article helpful, leave a comment.

## Further reading

- [Postman API documentation](https://learning.postman.com/docs/publishing-your-api/documenting-your-api/)
- [Get started with Node.js](https://nodejs.org/en/docs/guides/getting-started-guide)