Automated API Testing Using Postman
By Rameshwari Fegade, Kajal Bonde, Kishor Deshmukh, Sugat Bhagat and Kshitija Dale
Postman is a superb API testing tool for developers, QA testers and penetration testers. Its UI permits you to simply send HTTP requests and see responses, however it’s one of the best automation tool.
Reading this Postman tutorial will help you to
1. Creating test suites.
2. Storing information for running tests in various environments.
3. Storing data for other tests.
4. Move tests and environments to code repositories easily.
What is API Testing?
API testing could be a set of quality assurance actions that embody causation calls to the API, obtaining output, and substantiating the system’s response against the outlined input parameters, specially, the accuracy of knowledge and data’s format, communications protocol standing codes, and error codes.
Usually, API testing is performed on genus APIs made by the in-house development team. we tend to don’t take a look at third-party genus APIs, however we are able to take a look at the approach our software system accepts their requests.
The approach to API testing for the most part depends on the API kind. There are net genus APIs aka net services, info genus APIs that connect applications with decibel management systems, operational systems genus APIs, and remote genus APIs for accessing resources set outside the device requesting them.
Why You Should Automate API Tests?
Usually, API testing is performed on APIs produced by the in-house development team. We don’t test third-party APIs, but we can test the way our software accepts their requests.
The approach to API testing largely depends on the API type. There are web APIs aka web services, database APIs that connect applications with DB Management Systems , operating systems APIs, and remote APIs for accessing resources located outside the device requesting them. Why You Should Automate API Tests?
Testing in software system development is employed to determine the standard of any piece of software system. If you’re building genus API’s as a backend for one frontend application otherwise you are building genus API’s to be consumed by many services and shoppers, it’s vital that the genus API’s work evidently.
Setting up machine-driven API tests to check the various endpoints in your API can facilitate catch bugs as quickly as attainable.
It will additionally permit you to maneuver quickly and add new options as a result of you’ll merely run the check cases to examine if you break something on the approach.
Why Automation and Postman?
Automation is that the new norm across sectors. Automation, exploitation carrier in testing will improve and increase the depth and scope of tests for a stronger software package quality.
This carrier tutorial won’t solely assist you to grasp the machine-driven take a look anting method however additionally assist you to run carrier in chrome and introduce API automation to your daily QA processes for corporal punishment recurrent test cases.
What is the Need For Postman Automation?
Postman Automation is actually necessary whereas testing product with an oversized variety of integrations and/or frequent releases.
It is the last word tool for API automation. the most objective of QA automation is to scale back the combined quantity of effort needed for manually re-testing of a product that is fairly high.
Also, for removal of the manual testing efforts that area unit endowed in testing a collection of functionalities repeatedly.
For instance, Agile practices like continuous builds, the number of your time taken to receive a feedback for a manual regression check with the new code is just too high.
API testing is additionally referred to as Integration testing. Integration testing focuses on confirmative that the interactions of the many tiny parts will integrate along while not issue. Since API tests bypass the programmer, they have an inclination to be faster and far additional reparable than interface tests. Therefore, an honest QA team can build fairly correct projections supported the backlog at hand and also the general info regarding the project and its design and use automation for regression check.
So if you’re doing it in-house or choosing product outsourcing , mail carrier automation becomes progressively necessary because it automates the whole testing method and saves valuable time and resources.
Insights into Postman Tutorial for API Automation
Postman, a Chrome app is for interacting with HTTP APIs. Postman allows user to automate test cases in JavaScript with salient features like write test suites, build requests which will contain dynamic parameters, pass data between requests, etc.
For validation of API, on receiving a response, Postman validates the response as described within the test scripts. this is often performed under “Tests” section. Most interesting part may be a JSON response are often parsed to an array then the weather are often accessed by index and value or maybe be iterated.
The main advantage of using postman is that user doesn’t need to create a full JSON request programmatically unlike other automation API frameworks to place assert thereon. Postman beautifully designs them and helps user directly define test cases.
Tools/Dependency required to get started -
1). Postman
2). Node
3). Newman
Installing Postman from Chrome Browser
1). Visit https://chrome.google.com/webstore/category/extensions
2). Enter “Postman Chrome” in “Search the store” section
3). Click on “ADD TO CHROME”
Introduction to Newman
Newman is Postman’s collection runner engine that sends API requests, receives the response then runs your test against the response. It’s like postman’s instruction companion. It’s extensible then are often integrated into continuous integration servers and build systems.
Benefits of using Newman
Makes it easy to run a collection of tests using command line and gives ability to run a collection of tests written in postman right from within most build tools
Newman also allows to generate and store report directly from command line
How to install Node with Newman
For Windows Refer below blog-
http://blog.getpostman.com/2015/04/09/installing-newman-on-windows/
For Ubuntu follow below mentioned steps-
- Install Curl — sudo apt-get install curl
# Adding the NodeSource APT repository for Debian-based distributions repository AND the PGP key for verifying packages
• $ curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -
# Install Node.js from the Debian-based distributions repository
• $ sudo apt-get install -y nodejs
# Install newman from npm modules
• $ sudo npm install -g newman
Postman tutorial for Newman integration
Newman could be a companion tool for postman that runs Collections from the instruction.
Newman maintains feature parity with Postman and permits user to run collections in an exceedingly similar method they’re dead within the gathering runner within the postman app.
Example-
newman run postman_collection.json -e environment.postman_environment.json -g globals.postman_globals.json — reporters cli,html
Creating First script using postman:
Let us currently learn on the way to Create take a look at scripts mistreatment postman.
As we know, Postman allows to write the test scripts in Tests section. In our first script we will see how to check our response data.
• Open the postman app and enter the URL-
For Example https://reqres.in/api/users?page=2
• Choose GET method. (By default GET is selected)
• Now click on Tests section. (Below the url section)
• Copy-paste below test script in Tests section
//First Test Case
tests[“Status code is 200”] = responseCode.code === 200;
//Second Test Case
tests[“Body matches string”] = responseBody.has(“gob”);
//Third Test Case
var jsonData = JSON.parse(responseBody);
tests[“Response should have id of gob as 5: “ ] = jsonData.data[1].id === 5;
//Fourth Test Case
tests[“Response should have last name of gob as bluth” ] = jsonData.data[1].last_name === “bluth”;
Click on Send button.
Above example includes 4 test cases.
• The first test case is checking for the response code of API. The Pass condition for the test case should be 200 (response code).
• The second test case is validating for any key or value as- gob.
• The third test case is validating for a value of key id as 5 from JSON response.
• The fourth test case checking for the value of key “bluth” as “Newman” from JSON response.
Click on Tests as shown in image below to verify the test results.
Variables
In this Postman tutorial for Automated API testing, we are also going to cover variables. There are two types of variables- global and environment. Global variables are for all collections whereas the environment variables are defined for a specific set of collections as per the environment which can be selected from a drop-down or none can be selected.
Once defined, variables can be used for requests with format surrounded by curly brackets: {{VARIABLE_NAME}}. This can be seen in the image below.
The global variables can be consumed by any collection. So for any data that is accessible for all collections, we define them as global variables.
The data outlined for a particular surroundings is named as Environmental variable. We can select any one environment at a time for a collection or no environment as per choice.
• In Postman, at the top right section, click on (*) icon.
• Click on MANAGE ENVIRONMENTS (see the image below)
Pre-Request Script
Next we come to Pre-Request Scripts. As the name suggests, these scripts will run before tests. Postman lets users perform specific JavaScript coding to edit the data being sent along with the request. We can write these scripts in Tests section additionally however it’s an honest observe to separate these scripts in pre-request section because it are going to be dead before the Tests scripts.Here we can set Global and Environment Variable dynamically as well.
Please see the image below for the execution:
Copy-Paste the below code in Pre-request Script section in Postman-
postman.setGlobalVariable(“Token”, “MyDemoToken”);
postman.setEnvironmentVariable(“MyKey”, “MyDemoKey”);
postman.getGlobalVariable(“MyDemoKey”);
console.log(“Global Variable = “+postman.getGlobalVariable(“Token”));
console.log(“Environment Variable = “+postman.getEnvironmentVariable(“MyKey”));
- Select an environment from the dropdown located at the top right section of the screen.
• Click on “Send”
• Now go to Global and Environment variable section.
• Observe that keys have been set dynamically by the script.
To see the console output of script-
1. Type chrome://flags/ #debug-packed-apps in the URL bar in your Chrome browser window.
2. Look out for “Debugging for packed apps”.
3. Enable the setting.
4. Click on Relaunch Now once the setting is enabled.
5. Type chrome://inspect/#apps in the URL bar and then click “inspect”
Note: Collection Runner is opened as various instance of postman. To get the console output of collection runner, click on Inspect link of the respective instance from Apps section.
Feeding Test Data from CSV and Variable
A predetermined/hard coded value is never a good practice and will be a huge task when the number of test cases are increasing exponentially. It won’t be easy to maintain test scripts when your tests start failing due to structural or data changes.
Refer below link for getting data from CSV-
http://blog.getpostman.com/2014/10/28/using-csv-and-json-files-in-the-postman-collection-runner/
Refer below link for getting data from global and environment variables-
https://www.getpostman.com/docs/postman/environments_and_globals/variables
Let us consider an example for passing data with the help of CSV.
1. Place this code in Tests Script section in Postman :-
tests[“Status code is 200”] = responseCode.code === 200;
tests[“Body matches string”] = responseBody.has(“gob”);
var jsonData = JSON.parse(responseBody);
tests[“Response should have id of gob as 5: “ ] = jsonData.data[1].id === data.id;
tests[“Response should have last name of gob as bluth” ] = jsonData.data[1].last_name === data.name.trim();
console.log(“id =”+data.id+” “+”name =”+data.name);
2. Now we need to create a new collection to save the API. Follow the below steps to create a new collection.
• Click on Add button icon under Collections.
• Enter a Collection Name.
• Click on Create button.
• Once the Collection is created, click on Save button on right side of the screen.
• On Save Request pop-up, enter the Request name and select collection from the dropdown.
• Click on Save.
3. Now create a csv as illustrated below:
Example- g
id,name
5,bluth
4. With the help of the CSV, we run the test cases
- Open the collection runner.
• Click on “Run” button.
• Select No environment or the environment whose keys are consumed in your Tests.
• Select csv file under Data File (The file created in Step 3).
• In Data File Type, select CSV from dropdown.
• Click on Start Test.
Run Testcase from command line using newman
Now once the test cases are built, we need to pass it newman to run the scripts from the command line. The basic idea of running these tests using command line is that we can pass them to Jenkins further, which in return will run the test cases periodically. Now, to run the test cases in Newman, we need to export the test scripts and other information like URL, headers etc from postman in JSON format.
For more details refer below link-https://www.getpostman.com/docs/postman/collection_runs/command_line_integration_with_newman
Steps to export JSON for newman-
1. In postman, under Collections section, select the required collection.
2. Click on Export as shown in the image below.
3. Select “Collection v2”
4. Click on Export
5. Save this JSON
Now we need to export global and environment variables if the script requires any of them.
Steps to export JSON of global and environment variables for newman :-
- In postman, click on the (*) located at the top right section.
2. Click on Manage Environment
3. Now click on download icon placed against the environment name
4. Save the JSON on the same location where collection was saved
5. Now to download global variables,click on the “Globals” button placed at the bottom of the pop-up.
6. Click on “Download as JSON” button.
7. Save the JSON on the same location as others.
Now that we have all the JSON files required to run our test cases in Newman. The collection JSON contains all our test scripts, URL, Headers. Prerequisite Script, etc. contains most of the data except variables. The other two JSON files contain our key and values respectively.
Now it’s time to run our test cases from command line
Steps to run test cases from command line :-
• Open CMD
• Now open the folder where your JSON are saved
• Now hit command as below
newman run Test_Collection.postman_collection.json -e Environment.postman_environment.json -g globals.postman_globals.json -d demoData.csv — reporters cli,html
In this command -e represents environment variable, -g global variable, -d csv data file name, reporters cli, html represents output as console and
html reports.
Note: Replace respective file name in the above command.
Once the execution is completed, Newman will create an execution report in same folder.
Postman Tutorial for Best Practices of Automation testing
- Use trim function if data is retrieved as String from the CSV file.
- Add your pre-request data in Pre-request Script section.
- Use chrome developer console for debugging.
- Always confirm the length of an array for a test case. It will safeguard the script from failing due to any JavaScript exception
Example:
if(jsonData.data[0].length>2)
{
tests[“Response should have last name of gob as bluth” ] = jsonData.data[1].last_name === “bluth”;
Advantages of using Postman
- If API is updated and test is run in postman, it gives indication of failure. The API can then be updated for correct results.
- It can be used for performance testing of API.
- Postman can be utilized to perform load testing at scheduled time and record the status
- As the API’s are automated using postman there is less human involvement
Summary
We hope that this Automated API testing using Postman was helpful and we can conclude from the above information that API automation is a very important task in custom software development and the postman tool provides best facilities for all the requirements needed for an efficient API testing process. So try it out and get a grasp and an upper-hand on API’s.
References
https://www.postman.com/automated-testing/
https://learning.postman.com/docs/running-collections/using-newman-cli/integration-with-jenkins/
https://learning.postman.com/docs/running-collections/working-with-data-files/
https://learning.postman.com/docs/sending-requests/variables/