API Testing Tutorial – Part 2! Frequently Used API Code Snippets

This is the second part of a two part series on API testing. The first post looked at what is API testing. This post will look at how these API code snippets can help your API testing.

Postman is a Google Chrome app that helps you to create, save, send HTTP requests and test the response data.  It helps to automate the process of making API requests and testing API responses, allowing testers to establish a very efficient workflow. Most programmers and testers are familiar with Postman. However, many use it just to check the response for the services that they are working on. They are unaware of the powerful features that postman offers like: Collections, Tests and Pre-request scripts. In this article, I would like to give a quick overview of the test snippets provided by Postman.

The main reason I like Postman is because of its powerful automation capabilities. Moreover, the learning curve for using it is very low and the app provides a very clean and intuitive user interface to test your server requests. These tests will validate every single time if the response is correct. Writing tests in Postman is made easy by JavaScript and inbuilt snippets, allowing any inexperienced tester to write an efficient test.

Postman is a real time saver making it easier for developers to develop and test APIs. Postman drastically reduces the pressure of regression testing from the QA team. API automated tests are far less time consuming than UI automated tests. The major advantage of API automation is that we can access the application without a user interface. This provides an early evaluation of its overall build strength before running GUI tests.

 

Frequently Used API Code Snippets 

To begin writing a test, first click on the ‘Tests’ tab under Postman ’Builder’ tab. You can select a snippet that is on the right panel as shown below. This will generate a code template and you can modify it based on your context.

  • Snippet- ‘Status code is 200’
tests[“Status code is 200”] = responseCode.code === 200;

This is the most basic snippet which checks if the response code is 200(The request has succeeded). You can use the snippet as is, with most positive scenarios. For scenarios as logging in with invalid credentials you can assign the response to 400(Bad request).

tests[“Status code is 400”] = responseCode.code === 400;

  • Snippet- ‘Response time is less than 200ms’
tests[“Response time is less than 200ms”] = responseTime < 200;

This simple snippet checks if the response time was less than 200ms. You can modify it based on your context. For a scenario like uploading a large file you can edit this snippet as follows:

tests[“Response time is less than 1 minute”] = responseTime < 60000;

  • Snippet- ‘Response body: Contains string’
tests[“Body matches string”] =responseBody.has(“string_you_want_to_check“);

In case you are running a test that is attempting to log in with invalid credentials, assume that you will get a response like the one below. You can use this simple code to check for a string in the response.

Response Test What the test does
{  “errorCode”: “TAR_ERR400_06”,

  “statusCode”: 400,

  “message”: “Invalid credentials.”

}

 

tests[“Body has the string invalid credentials”] =responseBody.has(“Invalid credentials. “);

 

This test snippet will check the response for the string “Invalid credentials.
  • Snippet- ‘Response body: JSON value check’
var jsonData = JSON.parse(responseBody);tests[“Your test name”] = jsonData.value === 100;

 

In case  you are trying to login with invalid credentials, the test below will check if the ‘errorCode’ in the response is correct.

Response Test What the test does
{  “errorCode”: “TAR_ERR400_06”,

  “statusCode”: 400,

  “message”: “Invalid credentials.”

}

 

var data = JSON.parse(responseBody);tests[“errorcode “] = jsondata.errorCode === “TAR_ERR400_06”;

 

This test checks if the errorCode is: “TAR_ERR400_06”


Working with variables (Environment and global)

1. Environment Variables:
Environments- give you the ability to customize requests using variables. This way you can easily switch between different servers without changing your requests.

  • To add an environment click on ‘No environment’ on the top right corner of the screen
  • Click on ‘Manage Environment’
  • Click on ‘Add’ and set the environment name as ‘Test’
  • You Can add variables as key value pairs

For example :  URL   https://restqa.com

It is possible to create multiple environments and each could have a variable called ‘URL’-signifying the actual URL. For example, if we have 2 different environments called production (url:https://productionserver.com ) and QA (url: https://restqa.com), environment variables can be used in the form – {{variableName}}. The string {{variableName}} will be replaced with its corresponding value. Henceforth we can use the same request {{URL}}/userlogin and only switch the environment before running it.

After setting up the environments, you are just a click away from switching between environments.

  • Snippet- ‘Set an environment Variable’
    You can chain requests by extracting data from responses and assign them to an environment using test scripts. You can use the test snippet Set an environment Variable” to create an environment variable from your response data.
var jsonData = JSON.parse(responseBody);postman.setEnvironmentVariable(“variable_key”, “variable_value”);

 

Response {“userId”: 1161,
“name”: null,
“customerid”: 0,
“id”: 0,
“customers”: null,
“fname”: “”,
“lname”: “”,
“username”: “B_8QbRA
}
Test var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable
(“Userid”,jsonData. userId);
What the test does? This  parses the response body and assigns the value of ‘userId’ in the response data by creating an environment variable: ‘Userid’.

You can then pass the value ‘Userid’ in any of the next requests. An example below:

Assume 1172 is your user id in this request – https://restqa.com/get/1172

You can use the environment variable as https://restqa.com/get/{{UserId}}

 

Similarly you can use it in your request body as shown below:

{

“name”:”xyz”,

“userid”: “{{UserId}}”,

“label”: “Label2”

}

2.     Global Variables:

Global variables provide a set of variables that are always in scope. You can have multiple environments, and only one can be activated at a time.  There is going to be one set of global variables that are always going to be available. You can use them in the same way as the environment variables- {{variableName}}.

Clear Global and Environment variables:

You can always clear an environment variable or a global variable using the snippets below:

postman.clearGlobalVariable(“variable_key”);

postman.clearEnvironmentVariable(“variable_key”);

Tiny Vallidatr for JSON Data

Tiny Validator helps you to validate the schema of your response. An example below:

Response Test What does this test do?
{“userId”: 123,

“fname”: “Prashant”,

“lname”: “Hegde”,

“username”: “[email protected]”,

“role”: “admin”,

“projects”: 0,

“phoneNo”: null,

}

 

var schema = {“items”: {

“type”: “string”

}

};

var data1 = [jsonData.fname,jsonData.lname];

console.log(tv4.error);

tests[“Valid Data1”] = tv4.validate(data1, schema);

Checks if the fname and lname are strings.

Similarly validates the  entire response schema.

Postman is a real time saver making it easier for developers to develop and test APIs. Postman drastically reduces the pressure of regression testing from the QA team. API automated tests are far less time consuming than UI automated tests. The major advantage of API automation is that we can access the application without a user interface. This provides an early evaluation of its overall build strength before running GUI tests.

By integrating the API automated tests to the build server, the QA team can provide a quick feedback on the health of the application as soon as it is deployed. This is achievable with Newman, a command-line collection runner for Postman. It allows you to easily run a Postman collection directly from the command-line, and integrate it with your continuous integration server.

 


Share your thoughts about your API test automation process  😀 

What are the ways YOU use to supercharge your API testing?

 

About the Author

Prashant

Prashant Hegde is a passionate tester. He has ably led test teams to success in many organizations and helped them improve their application quality process. Prashant is an agile enthusiast and has worked in different roles on agile teams for the last five ten years. Prashant enjoys sharing his experiences by blogging and participating in agile communities around the world. Prashant is a Certified Scrum master and frequent speaker at industry conferences. Prashant has helped thousands of ISTQB aspirants to clear their certifications with his free app ISTQB test mentor. You can follow Prashant on his blog, website and on Twitter
Find out more about @prashant-hegde