Introduction

As a software developer, I believe that testing is as equally important as development. Testing aims to provide many benefits crucial for business success, such as: Verifying if users can effectively complete their tasks. It also helps uncover usability issues so that you can avoid redesign costs. Postman test script is one of the widely used testing methods that we’ll be learning.

If you have prior knowledge of Postman, you can skip this section. A postman is a top-rated tool for API development. It’s simple to use and enables collaboration to create better APIs because it has a user-friendly UI and a wide range of functionalities. In this article, we’ll use Postman to create, test, and secure an API.

You can download and install Postman. After completing the installation, launch the app.

The postman comes with loads of options, so seeing this screen for the first time may be confusing but don’t worry, let’s try to cover everything we need.

Type of Request: APIs have different requests. GET, POST, PUT, DELETE are the most used types.

Request URL: To enter the URL for our API endpoint instead of the Request Method Option, set to GET by default.

Body: The body section is used to include the data that needs to be sent.

Tests: This is an essential section related to this article. Scripts are written here to ensure our API is working properly.

Headers: Every request has its header type, which can be included with this section’s request.

That’s all you need to understand to jump into the next section. Don’t be amazed, but now you know the basics of the Postman. Now, let’s get ready with your favourite editor to write code and learn the best practices among web developers.

Installing The Project

Firstly, make sure that you have installed Node.js in your system. Node.js is an open-source, cross-platform, back-end, JavaScript runtime environment that executes JavaScript code outside a web browser. To verify you have installed Node.js, type “node -v.” in the terminal. This will return the installed version of Node, which states you have installed Node.js. If you haven’t installed Node.js, you can download and install it here.

Next, clone or download this GitHub repository as it contains all the files required for this project.

Next, create an .env file. Open the .env file and add the lines below:

Type “npm install” in the terminal which will install all the packages we need. Don’t forget to replace the username and password in MONGO_URI.

For this project, we’ll be using MongoDB as our database. MongoDB is a compelling and scalable NoSQL database with a wide variety of queries. Let’s make it and set it as accessible to the public. Don’t worry as we’ll be using a free database for this task. Please follow the steps in this link if you don’t know how to create a free MongoDB collection.

At this point, everything that we need for this project is complete. Now let’s focus on testing and securing the API.

Testing the API

Open the terminal and type “npm start”. You should see the output in the image below, indicating that our server is running successfully. The database is now connected.

Now, open Postman which was installed on the previous step and get ready to access your API. We’ll be testing three APIs and securing only one API for the database admin.

In the project that you’ve cloned or downloaded, two files were already created. The table below describes the methods that we’ll be using.

File Name Method Name Purpose
auth.js signup Signs in a new user and adds a new user to the database.
signin Signs in a new user, creates a token, and stores the token as a cookie.
signout Signs out user.
requireSignin User must be signed in to perform actions.
isAuth User must be authenticated.
isAdmin Only an admin can have access to this method.
user.js userById Saves user object as req.profile.

First, we’ll be testing the SignUp API. Enter http://localhost:8000/api/signup for the URL. Ensure that the type of request is POST. In the Headers tab, enter Content-type in the key column and application/json in the value column.

Then, open the Body tab. If you’ve seen the user model in the project, you’ll know that we have three required fields: email, password, and name. Select type as raw and JSON format.

Click Send and keep an eye on the response generated. The user object should look like the image below.

We’ll be using this response as a base to create our first test in Postman. According to the Postman documentation, we can use pm.response to get a response object and pm.test to write the test.

Let’s generate our first test script using JavaScript. By the end of the first test, you’ll understand how to create your test scripts.

First, store the JSON response in a jsonArray, then use the functions to check the status code and the user object.

var jsonArray = pm.response.json();
pm.test("Status code is 200", function () { pm.response.to.have.status(200); });
pm.test("User object exists",function (){pm.expect(jsonArray.user).not.equal(null)});

You’ve successfully written the test script for our first API. Now copy and paste this code to the Test tab of Postman.

Next, create a new user and see if our test script is working. Open the Body tab to change the email, name, or password, then click Send. In the Test results tab, you’ll see a green Pass icon to indicate the test was successful.

Let’s now test the second API. To access the SignIn API, change the URL to http://localhost:8000/api/signin, and make sure that the request method is set to POST. Ensure to include the email and password in the Body tab to sign in. When you click Send, the response object will be generated according to the Body tab.

It’s important to know that as soon as the user is signed in, a token with an expiry date is stored as cookies in your browser. Let’s now write a similar test script to check if our response object has the token.

In the next section, I’ll show you how to secure an API, which can only be accessed by the admin.

Securing The API

Open your project. You’ll see a small code that returns a user’s profile on a successful API call within the controller/user.js file. The routes/user.js file shows you that we’re importing many functions and middleware methods.

To access the GET method for http://localhost:8000/api/secret/:userId, the user must be signed In and must be Admin. Currently, we don’t have any admin users in the database so let’s try to access this API. To access this method, you need to sign in. We also need to add the token in the Headers tab as a bearer token described in the image below. To access this API, you need to add your UserId, which is generated when you SignIn or SignUp.

If you try to access this API without admin permissions, your access will be restricted by the server indicated by status code 403. When a new user signs in by default, we’re assigning a role to 0 (model/user.js). The isAdmin method then restricts permissions if the role is 0 (controller/auth.js). Now, let’s try changing the role to 1 and access the same API. We can use MongoDB Atlas software to access our database.

Let’s make the same API call. As you can see, you’re retrieving the response to secure your API, in which access is limited to a specific person.

Conclusion

With Postman, it is easy to test the REST API with test-scripts as it supports a wide range of functions and provides a user-friendly UI. By testing the API before moving them to the production environment, you ensure that your APIs are protected and effective. As cyber-attacks worldwide are increasing day-by-day, developers must secure the user’s data successfully.

We have used important industry-accepted technology and tools such as Postman, Node.js, Mongo DB, Express.js. Postman is quickly becoming a valuable part of every API test’s toolkit. If you’re looking for a more code-oriented approach, you can also use the npm package called Newman, which runs Postman collection in the command line. Then, you can deploy these files to Jenkins and establish webhooks to automate your tests.

How to work with us

  • Contact us to set up a call.
  • We will analyze your needs and recommend a content contract solution.
  • Sign on with ContentLab.
  • We deliver topic-curated, deeply technical content to you.

To get started, complete the form to the right to schedule a call with us.

Send this to a friend