logo logo

REST API Testing using Postman & Newman Essential Guide

main post image

API is the acronym for Application Programming Interface. It is a set of rules that allow programs to talk to each other. APIs are used to aid server-client communication.

REST determines how the API looks like. It stands for “REpresentational State Transfer”. It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL.

Each URL is called a Request while the data sent back to you is called a Response.

These are the Request Methods:

  • GET: Used to access a resource
  • POST: Used to create information
  • PUT: Used to update a resource
  • DELETE: Used to delete a resource

To learn more about APIs, I recommend the following resources:

  1. I have prepared a PPT which helps understand more about APIs. Check it out here!
  2. REST APIs are a powerful way to run tests and TestProject provides you with an Addon for RESTful API testing capabilities. The API Addon utilizes TestProject as a functional testing platform to create more powerful testing while combining API steps with functional UI test automation. The RESTful API Addon provides actions to send HTTP/S requests using GET, POST, PUT and DELETE methods. It is open source and you can tweak or update it according to your specific requirements to enhance it further 🚀
  3. For a complete API Testing Glossary, check out this list of definitions by Dave Westerveld!
  4. Prashant Hedge also wrote a tutorial to master API Test Automation in 10 mins you should definitely check out!

Note: This tutorial has been submitted as part of the TestProject Master Program – I invite you all to take part, contribute to the community and get really cool gifts and certificates! 👌


Table of Contents

  1. What is API and REST API
  2. Learn how to Automate REST API Testing
  3. Where to start? Postman!
  4. Writing Tests
  5. Create a Collection of API Calls
  6. Running the Collection via Command Prompt with Newman Plugin
  7. Summarizing Guide for Creating and Maintaining automated API tests: Step-by-step flowchart guide!

Learn How to Automate REST API Testing

GET http://dummy.restapiexample.com/api/v1/employees
POST http://dummy.restapiexample.com/api/v1/create
PUT http://dummy.restapiexample.com/api/v1/update/{{employeeId}}
DELETE http://dummy.restapiexample.com/api/v1/delete/{{employeeId}}

Definitions for the above APIs can be found here: http://dummy.restapiexample.com/

First, you need to list down the user flow which has to be automated. In our case, the scenario we are going to automate is:

  1. Get Full Employee List and Validate the first employee name [This is not necessary for our user flow, just added as a bonus 😉].
  2. Create a new Employee record and validate the record.
  3. Update the created employee record and validate the changes.
  4. Verify that the changes are reflected in the employee record.
  5. Delete the employee record and validate it.
  6. Verify that the deleted employee is removed from records.

Where To Start? Postman!

  1. Click on the Settings icon on the top right corner of Postman.
  2. Click on ‘Add’ from Manage Environments popup.
  3. Add Environment name and variable details (here we specify the URL as a variable) in order to make our API scripts reusable across different environments.
  4. Select the corresponding environment created from the select environment dropdown next to the settings icon.
  5. Now, from our main URL: http://dummy.restapiexample.com/api/v1/employees, we can replace the API address to the variable created. For example: {{url}}/api/v1/employees [Same goes for all API requests].

Writing Tests

After specifying the URL and selecting the method we can create a test script to validate our response code & response data.

In this example, we will be adding scripts for validating the response code of request and verifying the employee name for the first record:

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

pm.test("Check First Employee name", function () {
    
      var jsonData = pm.response.json();
      
      for(var i=0; i<jsonData.data.length; i++)
      
        {
             if (jsonData.data[i].employee_name==="Tiger Nixon")
               
                {
                    
                      pm.expect(jsonData.data[i].id).to.equal("1")
                }   
        }
});

This is how our first test looks like in Postman:

FirstTest_Postman_REST API Testing Tutorial

Click on Send and check the result of our test: Status of the test will be displayed in Test Results section. Try changing the expected code value to anything other than 200 and check the result. Failed, right? 🧐


Now that you’ve seen how to create a test to validate your request, let’s move to automation! Testing several API requests one by one can become a repetitive and tiring task, hence we need to automate our API tests.

Create a Collection of API Calls

A collection is a place where you will group all your API calls. After creating the environment click again on New >> Collection give a name and add a description (Optional) to your collection and then click on create.

Once this is done, you can import a file, import a folder, import from a link or paste the JSON Raw Text, for testing purposes we will be using the following collection as our reference:

https://www.getpostman.com/collections/c4dd41bc0c91b3bc79b4

In this collection, I already added some tests for all the API requests which we can map to the scenarios which we discussed in “The scenario we are going to automate” section above. Once the automated test cases have been defined within each request and all requests are ready, we will use Runner as a way to make all calls at once. If you imported correctly, 6 calls will appear within our request, as seen in the image below:

REST API Testing_Postman After Import_List of Requests in Collection

Now, Click on “Runner” which will be opened in a new window. Then specify the collection to be executed (collection imported in the previous steps), select the Environment created previously, the number of Iterations that defines how many times the collection will be executed and finally click on RUN. Here is the Postman Runner Window:

REST API Testing_Postman Runner Window

In the end, reports of each execution are displayed, as well as the tests that have passed and/or failed. You can also re-run the tests, create a new run or export your results. In the image below you can see Postman’s execution result:

REST API Testing_Postman Execution Results

Running the Collection via Command Prompt with Newman Plugin

Now let’s go a little further and run it using Newman if you intend to use your tests together with any continuous integration tool, for example, Jenkins. Newman works similarly to Postman but is run via the command line, that is, in the terminal, you will be able to run your tests using npm commands.

Installation & run commands can be referred to here: https://www.npmjs.com/package/newman.

The first thing that needs to be done is to export your collection, Select Collection v2 and then click on export, give a short name to avoid typing a very big name. It will download a JSON file with all the items in the collection we selected. Also, download the environment from Manage Environment popup:

Postman Export Collection    Manage Environment popup

Open terminal and install newman using the command: npm install -g newman, then navigate to the location where the JSON (collection) file is saved.

For executing, enter the command “newman run employee_data.json -e demo-data.json” In which “employee_data.json” is the collection and “demo-data.json” is the environment JSON downloaded earlier.

All the test results, the number of iterations used, the number of requests, test scripts and validated assertions will be displayed in the terminal on executing the command:

Newman Execution

You can also export your results to html, for this we need to install “newman-reporter-html”, and execute “newman run employee_data.json -e demo-data.json -r html” which will generate HTML report in the same folder where the collection is exported inside a folder called newman.

The API Collection, Environment JSON & Newman report generated can be accessed from my GitHub repository: https://github.com/nithin-cy/PostmanDemo.git


Summarizing Guide for Creating and Maintaining automated API tests

This is just basics so expect more to come in upcoming articles… 🤯
I’d like to conclude this REST API Testing tutorial with the following flowchart I’ve made to help you create and maintain your automates API testing efforts:

Creating and Maintaining Automated API Testing - TestProject.io

Happy Coding! 😃

 

Avatar

About the author

Nithin

An ISTQB certified professional with 6+ years of experience in the field of IT with focus on Quality Assurance (Automation & Manual) of web and mobile based (native & hybrid technologies) applications. Dedicated and hard-working individual with good communication and team-building skills & also good in managing multiple tasks in a pressured environment. Believes in doing high quality, thorough work and clear, honest, straight forward communication with Co-workers and superiors. Senior QA Automation Engineer at Fave. More articles by him can be found here : synapse-qa.com

Join TestProject Community

Get full access to the world's first cloud-based, open source friendly testing community. Enjoy TestProject's end-to-end test automation Platform, Forum, Blog and Docs - All for FREE.

Join Us Now  

Comments

10 1 comment

Leave a Reply

popup image

Best In Class Java and C# SDK

Join thousands of automation developers using TestProject to supercharge open source testing, with a Selenium and Appium SDK, supporting Java and .NET Core (C#)!
Sign Up Now right arrow
FacebookLinkedInTwitterEmail