API Testing using Postman scripts

Apisero
6 min readFeb 4, 2021

--

Author: Shweta Amilkanthwar

Introduction:

You can write test scripts for your Postman API requests in JavaScript. Tests allow you to ensure that your API is working as expected, to establish that integrations between services are functioning reliably, and to verify that new developments haven’t broken any existing functionality

Postman scripting is used to ensure that a new change to the code did not break existing functionality.

You can add tests to individual requests, folders, and collections.

What is a test in Postman?

With Postman, you can add scripts to your request to use dynamic variables, pass data between requests, and write tests.

  • Pre-request Script: pre-request scripts used to execute before a request runs
  • Tests: allow you to ensure that your API is working as expected. Tests will execute after the response is received, so when you Send a request, Postman will run your test script when the response data returned from the API.

Variables in Postman:

Variables allow you to store and reuse values in your requests and scripts. By storing a value in a variable, you can reference it throughout your collections, environments, and requests.

Postman supports the following variable scopes:

  • Global
  • Collection
  • Environment
  • Data
  • Local

If a variable with the same name is declared in two different scopes, the value stored in the variable with the narrowest scope will be used — for example, if there is a global and a local variable both named username, the local value will be used when the request runs

  • Global variable: allow you to access data between collections, requests, test scripts, and environments. Global variables are available throughout a workspace.

Set value for global variable:pm.globals.set(“variable_key”, “variable_value”);

Get value for global variable :pm.globals.get(“variable_key”);

  • Collection Variable: are available throughout the requests in a collection and are independent of environments.

To create or edit a variable for an existing collection, select the collection in Collections on the left of the Postman app, open the View more actions (…) menu, and click Edit

Set value for collection variable: pm.collectionVariables.set(“variable_key”, “variable_value”);

Get value for collection variable : pm.collectionVariables.get(“variable_key”);

  • Environment variables: allow you to tailor your processing to different environments.Only one environment can be active at a time

Set value for Environment variable: pm.environment.set(“variable_key”, “variable_value”);

Get value for Environment variable : pm.environment.get(“variable_key”);

  • Local variables:are temporary, and only accessible in your request scripts

Set value for Local variable: pm.variables.get(variable_key”, “variable_value”);

Get value for Local variable: pm.variables.get(“variable_key”);

Dynamic variables

Postman provides dynamic variables that you can use in your requests.

  1. $guid: generate uuid dynamically
  2. $randomAlphaNumeric: random alpha-numeric character
  3. $randomInt: random integer between 1 and 1000
  4. $randomIP: random IPv4 address
  5. $randomFirstName: random first name
  6. $randomLastName: random last name
  7. $randomPhoneNumber: random 10-digit phone number
  8. $randomCity: random city name
  9. $randomCompanyName : random company name
  10. $randomEmail: random email address

Writing scripts:

Let’s start writing scripts for API:

I have an api which performs POST,PATCH,GET and DELETE operation on database.

Below is my request to add an employee to the database.

I have made id, first name, last name, salary, and address dynamic using dynamic variables. I am taking emp-host from collection variables which I have declared at collection level.

We can access those variables in request by enclosing them with double curly braces.

In the image below I have added test cases in ‘TEST ’ section.

1

var reqBody=JSON.parse(pm.request.body);

console.log(reqBody);

Here I am storing request body data into the reqBody variable and using console.log I am printing request data into the console.

2

var responseData = pm.response.json();

console.log(responseData);

Here I am storing response from API responseData variable and using console.log I am printing request data into the console.

pm.test(“Success:Status code is 201”, function () {

pm.response.to.have.status(201);

});

3

In the above test case I am checking whether API returned status code as 201 or not. If API does not return 201 code the test case will fail. Here my test case name is ‘Success:Status code is 201’

4

pm.test(“Response is valid”, function () {

pm.response.to.be.withBody;

pm.response.to.be.json;

});

In the above test case I am checking whether API returned response with body and data as json or not. Here my test case name is ‘Response is valid’

5

Var schema= your response json schema. (You can generate schema using https://jsonschema.net/home)

pm.test(‘Schema validation’, function () {

var result = tv4.validateResult(pm.response.json(), schema);

if (!result.valid) {

console.log(result)

}

pm.expect(result.valid).to.be.true;

});

Here I am validating responses with a schema which I have declared in the variable schema or not.

In the test result section you we will get to know what all scripts are passed,failed,skipped

6pm.environment.set(“employee-id”,reqBody.id)

Using the above syntax I am storing id of employee created in DB into an environment variable. So that we can use this variable in our get call.

GET employee details call on DB

In the below image, I am calling a GET employee by id. In earlier request I have saved employee id in the environment variable. And that variable I am using in the URL.

The GET response from API is as below:

[

{

“firstname”: “Adelle”,

“address”: “Port Petra”,

“id”: 812,

“salary”: 62341,

“lastname”: “Nienow”

}

]

In the ‘Tests’ of GET request I am adding two more test cases.

One is to check whether the first name is string or not

And second one is to check whether the id is a number or not.

  • Setting headers:
  • If your request has any headers. You can take headers value from variables and can declare headers in the pre request section at collection,folder or request level.

Syntax to declare headers in pre request section:

pm.request.headers.add({key: ‘audit_user_type’, value: ‘{{audit_user_type}}’});

pm.request.headers.add({key: ‘correlationId’, value: ‘{{correlation-id}}’})

Here audit_user_type and correlation-id defined in environment / collection variables.

  • Sending requests from scripts

You can use the pm.sendRequest method to send a request asynchronously from a Pre-request or Test script

Example of pm.sendRequest:

pm.sendRequest({

url: https://postman-echo.com/get,

method: “GET”,

header: {

‘app_name’:pm.environment.get(‘app_name’),

‘audit_user’: pm.environment.get(‘audit_user’),

‘audit_user_type’:pm.environment.get(‘audit_user_type’),

‘audit_event_id’:pm.environment.get(‘audit_event_id’),

‘audit_app’:pm.environment.get(‘audit_app’)

},

body: {

mode: ‘raw’,

}

}, function (error, res) {

if (error) {

console.log(error);

} else {

console.log(response);

}

pm.test(‘response should be okay to process’, () => {

pm.expect(error).to.equal(null);

pm.expect(response).to.have.property(‘code’, 200);

pm.expect(response).to.have.property(‘status’, ‘OK’);

});

});});

References:

https://learning.postman.com/docs/writing-scripts/intro-to-scripts

https://learning.postman.com/docs/writing-scripts/script-references/variables-list

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference

https://learning.postman.com/docs/running-collections/intro-to-collection-runs

https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/#sending-requests-from-scripts

--

--

Responses (1)