Rest API Testing with Postman: An Introduction

Testing of Rest APIs is one of the most important tasks in application development. A good strategy of approach can detect many errors before the release of the application.

There are now many tools on the Internet for testing Rest APIs. All tools certainly have the most important functions. I use Postman, because I like it the most and it is very intuitive and completely free. In addition, I would like to show you how to select good test cases and what is important to keep in mind.

If you are working with several people on a shared Rest API, Postman offers a subscription to make working in a team much easier. I’m only referring to the free version here.

You can download Postman here (available for Windows, Mac & Linux).

Rest APIs can be developed well with the help of Node.js. If you want to know more about it, feel free to go through my Node.js beginner’s guide.

Just to reiterate what a Rest API actually is:
A Rest API is the interface between client and server, which can request and send data via simple HTTP requests. Every time you call a URL in the browser, at least one HTTP request to the server happens in the background.

1. Selection of the optimal test cases

Before we enter the requests into Postman and start testing, the first step is to select the test cases. This requires a bit of brain power and also a bit of practice – but is extremely important so that we uncover all potential bugs.

We need to think particularly carefully about edge cases. Edge cases are test inputs that are most likely to cause erroneous output or even a program error. Before that, however, we need to clarify two basic concepts:

1.1. HTTP Request Methods

The individual URLs of a Rest API (routes in programming) all have a specific HTTP request method. There are quite a few of these. These are the four most important of a Rest API:

  • GET: To retrieve information from the server, e.g. username of a specific ID.
  • POST: To send information to the server, which then creates a new user in the database, for example.
  • PUT: To create or update an entity on the server
  • DELETE: To delete an entity on the server

A complete list of all HTTP request methods can be found here.

When developing the Rest API, you should already make sure that you select the right method for each route. I explain how this can look in my tutorial on creating a Rest API for a login system.

1.2. HTTP Status Codes

For each HTTP request, the server responds with an HTTP response, which always contains an HTTP status code. This returns the status of the requested operation. Mostly this is 200 (OK). This is the server’s way of saying that everything is OK.

You should already return these status codes in the correct use case when developing your Rest API, which will also make testing easier. Another example: If a user requests a URL for which he has no permissions because he is not authorized (not logged in), your Rest API should also return the status code 401 (Unauthorized) with a corresponding error message.

The most used status codes are:

  • 200 (OK) – Example: Request was executed without problems
  • 201 (Created) – Example: New user was created in the database
  • 400 (Bad Request) – Example: Missing parameters when calling
  • 401 (Unauthorized) – Example: User has no permission for a URL

A detailed list of important HTTP status codes can be found here.

1.3. Assemble test cases

Now it gets a bit more exhausting. You now have to select the appropriate test cases for your app. As already mentioned, we have to look especially at the edge cases. To explain this better, I have created the following requirements as an example:

  1. We want to create a function to register a user (/sign-up)
  2. Username, password and password repetition are to be queried
  3. The user name must not be assigned yet
  4. The user should receive an email to complete the registration (double opt-in)

With a little logical thinking, the following test cases come to mind first:

  • Were all parameters (user name, password, password repetition) passed?
  • Does the username already exist in the database?
  • Has the confirmation email been sent?

This is all correct, however, we have forgotten some. And these are the so-called edge cases:

  • Is the HTTP request method correct?
  • Do the password and password repetition match?
  • Could the database query be executed without errors?
  • Are the correct HTTP status codes returned in case of errors?
  • Is the username not too long for the database field (e.g. if VARCHAR is limited to 255 characters)?
  • Was a valid token for the double opt-in created and successfully stored in the database?

The aim is to look at the request from a different angle in order to cover all marginal cases as far as possible. I hope that I can sensitize you a little with this example.

Take some time to select the test cases. This is more important than running the tests. Once you have done this properly, you will save a lot of time in the future.

2. Organize requests in Postman

Now that we have selected the test cases, we start entering the tests into Postman, structuring them and, of course, testing them. If you have installed Postman, this interface awaits you.

You should create a separate collection for each project/Rest API. This is like a folder in which you can organize your individual requests. Also, you can then run the tests for all the requests in it with a single click.

Postman - Create Collection
Postman – Create Collection

We can then create any number of requests per collection. I have marked the most important settings in red.

Structure of an HTTP request
Structure of an HTTP request

First, we should give our request a name to quickly recognize it (“Login” in this case). This name also appears on the left side of the Collection menu.

Next, we can set the appropriate HTTP request method for each request and specify the exact URL of the Rest API route to check.

On the far right you will find the “Send” button to send a request directly.

2.1. Pass body data

In many cases we want to send data to the Rest API. We can either do this using the “Params” tab. These are then transmitted to the server according to the HTTP request method or we use the “Body” tab to transmit data in other data formats.

On the web, JSON is often used because it is very flexible and you can safely transfer complex data structures. It is important that you select “raw” above the text field and then select the format “JSON” to the right. Otherwise the data might not be transferred correctly.

Pass body parameters in Postman
Pass body parameters in Postman

In the large text field, the data can now be passed in JSON format.

This can look like this. Postman shows you errors in the JSON structure directly. But you can test it more exactly with this JSON validator.

{
"username": "webdeasy.de",
"password": "f00b4r",
"password_repeat": "foob4r"
}

Whether you use URL parameters or body data depends entirely on the implementation of your RestAPI. This is how you access it in Node.js respectively:

router.post('/sign-up', (req, res, next) => {
	// body data
	console.log(req.body.YOURDATA);
	
	// url parameters
	console.log(req.params.YOURPARAM)
});

2.2. Insert Authorization Keys

If you have implemented a login with a Bearer Token, you can transfer it in the “Authorization” tab. To do so, select “Bearer Token” and enter it under “Token” on the right.

Authorization - Transmit Bearer Token
Authorization – Transmit Bearer Token

For other authentication methods, you can select the appropriate one under “Type”.

Tip: Under the menu item “History” you can find your last queries.

3. Program test cases in Postman

We have entered the individual routes and structured them neatly. You can already execute and test them via the “Send” button. But you always have to check all results manually. It is easier if a script takes over the task for us. We can do that under the tab “Tests”.

Create test cases with Postman
Create test cases with Postman

Here you have the possibility to program your test cases, which is also easier than it sounds at first moment.

We can realize the query of the correct status code via the following code:

pm.test("Status test", function () {
    pm.response.to.have.status(200);
});

It can be as simple as that. What you will also often need is to query a response header variable. Here I check if the response is an image of type “jpeg”:

pm.test("Content-Type is image/jpeg", function () {
   pm.response.to.have.header("Content-Type");
   pm.response.to.be.header("Content-Type", "image/jpeg");
});

Tip: In the right margin under “Snippets” you can click to insert predefined tests.

A more detailed documentation on how to create test cases is available directly from learning.postman.com.

4. Execute tests automatically

We have created our test cases manually. But to save us some time, we can run all tests together in one collection. To do this, select the collection and click on “Run”. There you can set the number of iterations (executions) and other items.

Run Collection Test
Run Collection Test

Afterwards, you will receive an accurate test protocol and can directly fix errors in the code and run the test again.

Test protocol of the two tests
Test protocol of the two tests

Summary

When testing a Rest API (and in general), the selection of test cases is an extremely important step. Only if you choose everything correctly, you can cover all edge cases and fix all potential bugs in your application. Postman offers you a simple interface for testing and trial and error. With a few simple steps, you can customize Postman so that you only have to make a few adjustments to your next application and thus save a lot of time.

Note: For large and very sensitive systems, many more and more detailed tests have to be created and evaluated (integration tests, acceptance tests, …). In my experience, the examples shown here are well suited for many web applications to detect many errors and log results – especially after system adjustments.

Related Posts
Join the Conversation

7 Comments

Your email address will not be published. Required fields are marked *

bold italic underline strikeThrough
insertOrderedList insertUnorderedList outdent indent
removeFormat
createLink unlink
code

This can also interest you