DEV Community

AbId KhAn
AbId KhAn

Posted on

Automate API Testing using Postman & Newman


Postman is one of the most used tools for a developer. Most of the time, we develop APIs and test those individually. But in some scenarios, we have to test APIs in batch if they are dependent on each other. By utilizing the knowledge, we can do our tasks easier as well as minimize the repeating tasks. Through this, our dev testing time can be reduced.



In this task, we are using Json placeholder APIs. Postman has the feature to create assertion in the Tests tab. Also, it has the Pre-request script tab to run the script before API request. To minimize the complexity, we are checking only the returned status code of the Tests tab and set variables accordingly.
A snippet to set variables in the POST request body is given below.

   "userId": {{userId}},
   "title": "{{title}}",
   "body": "{{body}}"
Enter fullscreen mode Exit fullscreen mode

Some most used snippets are already attached beside the Tests tab in Postman to make it easy. A snippet of assertion to check status code is shared below.

pm.test("Successful POST request", function () {
   pm.expect(pm.response.code)[201, 202]);
Enter fullscreen mode Exit fullscreen mode

Afterward, we are adding the below code to set variables in Postman to use it later. This is like just another Javascript code.

const response = pm.response.json();
if (response && {
   let pid =;
   pm.environment.set("postId", pid);
Enter fullscreen mode Exit fullscreen mode

Now we can use this postId variable in another API request inside the header, body, URL or query parameter.
Now the most interesting part comes, that is, how can we set the variables automatically? We can use Postman runner to do the job. But for this task, we will use the Newman tool. To do so, we will create a CSV file with the header of the variable names (e.g userId, title, body). Now, we can run the below command to request with the CSV file data.

newman run ./jsonplaceholder.postman_collection.json \
   -d ./sample_posts.csv \
   --timeout 300000 \
   --global-var json_placeholder= \
Enter fullscreen mode Exit fullscreen mode

Also, we can request a specific folder of the collection with the --folder flag. Try to search for the --reporters flag and its usage.
A Github repo automate-api-testing-using-postman is made to review with the document.


Last but not the least, with Newman, we can get a html-like report view where we can easily get the request/ response information or CSV report if the request volume is high. Finally, we can focus on test cases that are more necessary for developer speed.

Top comments (0)