Generate Postman collections using Node JS
Introduction
Postman is a popular software which makes API development easier and faster. It provides functionality to create HTTP requests and testing them. In this blog, I will show how you can generate a postman collections programmatically using Node JS. I will also show how you can add tests to your requests, making API testing easier.
Background
Recently, me and my team at work were developing a software which had numerous APIs, with multiple scenarios for each API. Writing unit tests for each of these scenarios was time consuming. And, with the deadline approaching, we turned to Postman sandbox for writing tests.
For these tests, we used Node JS, to programmatically generate the postman collections, which contains the various scenarios for our application. We put the various user inputs in excel, and generated the tests after reading this excel sheet. Without any further ado, let me show how we tackled the problem, and how you can too generate postman collections programmatically using Node JS
1. Installing Dependency
To create the postman collection JSON, we will be using npm module postman-colection
. To install this dependency in your project, use the following command:
npm i postman-collection
2. Create an empty collection
We will create an empty collection. We will later add our requests to this collection
3. Create request header
First, we will create the request header. The following code achieves this:
In the above code, we declare a variable which contains our header as string. The different keys of headers are separated by new line (\n
) character. We then use the npm module to first parse the string and then convert it to header which can be directly consumed by Postman
4. Create request payload
Now that we have our headers created. We will create the payload for the request. At the same time, we will also declare a variable containing our API endpoint
5. Create tests for the request
We will now add tests for our API. Our tests will be contained in a template string. This template string will be copied as-is into our final collection JSON
6. Adding the request to the collection
Now that we have our request header, payload and tests created. We can add the request to our collection. The following code demonstrate that:
In the above code, on line 2, we create a new item. On line 5, we add our header to the item. We add payload and tests on line 10 and 19 respectively
7. Exporting the collection
This is the final step. We will now export the collection to a JSON file. This file can be imported into postman
Final Code
The final code is also available at my Github repository.