- Teri Eyenike
Testing web applications, both frontend and backend project, is important 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 major issues with the app, like identifying bugs within the code and fixing it 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, 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.
Source code
The complete source code for this project is in this repo.
Prerequisites
The following are required to complete this tutorial:
Download the Postman app
Basic knowledge of Node.js
Have Node installed on your local machine
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:
mkdir api-testing
Next, navigate to the directory and initialize the directory with the following command:
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 next package to install is nodemon which would be a dev dependency. That means it is only required to run during local development and testing.
npm install nodemon -D
Configure the package.json file
Change the values in the scripts section of the file with the following:
{
...
"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:
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:
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 of the controllers using its corresponding HTTP request.
Create a new folder called routes with a new file, friends.router.js, with each router attached to the endpoint.
Copy and paste this code:
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.
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:
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.
Give your workspace a name and set the visibility to Public. Thereafter, 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.
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
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:
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 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:
Creating documentation for test APIs
Documenting your API workflow is essential, just like how developers create a README.md file for every GitHub project they create. Similarly, it is possible to do the same in Postman.
At the right pane of the app, Select the Documentation icon.
Once opened, you can write a detailed request description of each endpoint in your collection by clicking the pencil icon to begin on hover of the text
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
Get started with Node.js
Top comments (0)