Getting started with Scripting in the Postman - GeeksforGeeks (2024)

Last Updated : 27 Oct, 2023

Summarize

Comments

Improve

Postman is a powerful tool for testing and automating APIs, and one of its most valuable features is the ability to write and execute scripts. With scripting in Postman, you can add dynamic behavior, automate repetitive tasks, and extract data from responses. In this article, we’ll go through the basics of scripting in Postman. Make sure you have Postman installed on your desktop. If not download it from the official website of Postman.

Why scripting in Postman?

Scripting in Postman opens up a world of possibilities for enhancing your API testing and automation workflow. Here are a few reasons why you might want to use scripting in Postman:

  1. Dynamic test data: You can generate dynamic test data as you execute scripts like people names, city names, phone numbers, pin codes, and so on. Thus, you don’t need to bother yourself with producing test data.
  2. Response validation: You can write scripts to validate the responses you receive, ensuring they meet your expected criteria. For example, Does the response have status code 200? Does the response body have a afterwardcorrected schema? This helps you catch unexpected changes and detect errors in the API.
  3. Automation: You can automate your testing workflows by writing scripts that execute a series of requests that are related to each other and validate responses automatically. For instance, you can simulate tasks like authentication and generating some data and then deleting it afterwardand using a series of GET, POST, PUT, DELETE requests. This is particularly helpful for creating complex testing workflows.
  4. Data Extraction: You can extract data from responses and store it as environment variables to use it in subsequent requests. This is useful for scenarios where you need to capture tokens, session IDs, or other dynamic values.

There are two types of scripts in Postman:

  1. Pre-request script: These scripts run before sending a request. These are used for doing some setup required before sending the request like setting some headers, cookies, generating request body etc.
  2. Test scripts: These scripts run after the response is received. They are used to validate the response body, check status codes, perform various assertions and so on.

Writing scripts in Postman

Writing test scripts in Postman is as simple as writing JavaScript since Postman scripts uses JavaScript language.

To write pre-request scripts go to pre-request scripts tab and to write test scripts go to Tests tab.

Variables in Postman test scripts

There are 4 types of variables in Postman:

  1. Environment variables: Environment variables enable you to scope your work to different environments, for example local development versus testing or production. One environment can be active at a time. If you have a single environment, using collection variables can be more efficient, but environments enable you to specify role-based access levels. Create and manage them in the “Environment” section of Postman. Access them using pm.environment.get(‘variableName’) in scripts.
  2. Collection variables: Collection variables are available throughout the requests in a collection and are independent of environments. Collection variables don’t change based on the selected environment. Collection variables are suitable if you’re using a single environment, for example for auth or URL details. Define them in the “Variables” section of your collection. Access them using pm.collectionVariables.get(‘variableName’) in scripts.
  3. Local variables: Local variables are temporary variables that are accessed in your request scripts. Local variable values are scoped to a single request or collection run, and are no longer available when the run is complete. Local variables are suitable if you need a value to override all other variable scopes but don’t want the value to persist once execution has ended. Set them directly in the script using pm.variables.set(‘variableName’, ‘value’). Access them using pm.variables.get(‘variableName’) within the same script.
  4. Global Variables: Global variables enable you to access data between collections, requests, test scripts, and environments. Global variables are available throughout a workspace. Since global variables have the broadest scope available in Postman, they’re well-suited for testing and prototyping. In later development phases, use more specific scopes. Define them in the “Global” section of your workspace. Access them using pm.globals.get(‘variableName’) in scripts.

Pre request scripts examples: To access the request properties in postman you can pm.request

Javascript

// Set a custom header

pm.request.headers.add({

key: 'Authorization',

value: 'Bearer <YourAccessTokenHere>'

});

// Set a query parameter

pm.request.url.addQueryParams({ page: 1 });

// generating fake data for request body

let obj = {

fname: pm.variables.replaceIn('{{$randomFirstName}}'),

lname: pm.variables.replaceIn('{{$randomLastName}}'),

country: pm.variables.replaceIn('{{$randomCountry}}')

}

pm.request.body.raw = JSON.stringify(obj);

// setting environment and collection varaibles variables

pm.environment.set('id', 14234233);

pm.collectionVariables.set('uid', 93782937);

// getting environemnt variables

pm.environment.get('id');

pm.collectionVariables.get('uid');

// sending requests

pm.sendRequest({

method: 'GET',

});

Test scripts examples

A test scripts can contain multiple pm.test() calls. Each call to pm.test() is for testing one parameter of the response.

Validate response status code

Javascript

// Check if the response status code is 200 (OK)

pm.test('Status code is 200', function () {

// assertion to check if status code is 200 or not

// if assertion is true then test passes else test fails

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

});

Check response body JSON has a certain field

Javascript

// Parse the response JSON

const responseBody = pm.response.json();

// Check if a property exists in the response

pm.test('Response contains the "username" property', function () {

pm.expect(responseBody).to.have.property('username');

});

Response body JSON property value validation

Javascript

// Parse the response JSON

const responseBody = pm.response.json();

// Check if a property has an expected value

pm.test('Username is correct', function () {

pm.expect(responseBody.username).to.eql('expected_username');

});

Response time validation

Javascript

// Check if the response time is less than 500 ms

pm.test('Response time is acceptable', function () {

pm.expect(pm.response.responseTime).to.be.below(500);

});

Handling Authentication

Javascript

// Obtain an access token from a previous response and set it as a variable

const accessToken = pm.response.json().access_token;

pm.environment.set('access_token', accessToken);

// Set the access token as an authorization header

pm.request.headers.add({

key: 'Authorization',

value: `Bearer ${accessToken}`

});

There are many snippets available in Postman test scripts. They can be found on the right side of the test script editor.

Postman has built in functionality of generating fake data. You can know more about it here.

A simple test script in Postman

We looked at some basics scripting examples in the above code samples. Let’s create a real test script for a GET request to implement our learnings. You can go ahead and try to write some tests by yourself!

Example: Method – GET

Javascript

// Check if the response status code is 200 (OK)

pm.test("Status code is 200", function () {

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

});

// Parse the response JSON

const jsonData = pm.response.json();

// Check if the response contains specific properties

pm.test("Response contains userId", function () {

pm.expect(jsonData.userId).to.exist;

});

pm.test("Response contains id", function () {

pm.expect(jsonData.id).to.exist;

});

pm.test("Response contains title", function () {

pm.expect(jsonData.title).to.exist;

});

pm.test("Response contains body", function () {

pm.expect(jsonData.body).to.exist;

});

Now hit the send button and look the tests passing successfully in the result bar. At last, our efforts paid off.

Getting started with Scripting in the Postman - GeeksforGeeks (1)



M

moonpatel2003

Getting started with Scripting in the Postman - GeeksforGeeks (2)

Improve

Previous Article

Postman Dynamic Variables

Next Article

Sending a Post request in postman pre-script

Please Login to comment...

Getting started with Scripting in the Postman - GeeksforGeeks (2024)
Top Articles
CoinDCX vs CoinSwitch: Which App is Best for Cryptocurrency
Is Trading a Sin?
Dte Outage Map Woodhaven
No Limit Telegram Channel
Txtvrfy Sheridan Wy
Seething Storm 5E
Erskine Plus Portal
Directions To 401 East Chestnut Street Louisville Kentucky
Jet Ski Rental Conneaut Lake Pa
Walthampatch
fort smith farm & garden - craigslist
Pac Man Deviantart
Bnsf.com/Workforce Hub
Munich residents spend the most online for food
Me Cojo A Mama Borracha
Wicked Local Plymouth Police Log 2022
Is Grande Internet Down In My Area
Wausau Obits Legacy
Talbots.dayforce.com
Eine Band wie ein Baum
Quadcitiesdaily
Is A Daytona Faster Than A Scat Pack
Amazing Lash Studio Casa Linda
104 Presidential Ct Lafayette La 70503
Local Collector Buying Old Motorcycles Z1 KZ900 KZ 900 KZ1000 Kawasaki - wanted - by dealer - sale - craigslist
§ 855 BGB - Besitzdiener - Gesetze
Culver's.comsummerofsmiles
Lilpeachbutt69 Stephanie Chavez
Www Mydocbill Rada
Log in or sign up to view
Productos para el Cuidado del Cabello Después de un Alisado: Tips y Consejos
Home Auctions - Real Estate Auctions
Kltv Com Big Red Box
2487872771
Petsmart Distribution Center Jobs
1400 Kg To Lb
Blue Beetle Movie Tickets and Showtimes Near Me | Regal
Hermann Memorial Urgent Care Near Me
Ket2 Schedule
Natashas Bedroom - Slave Commands
Tugboat Information
5 Tips To Throw A Fun Halloween Party For Adults
Tripadvisor Vancouver Restaurants
Chathuram Movie Download
All Weapon Perks and Status Effects - Conan Exiles | Game...
Oakley Rae (Social Media Star) – Bio, Net Worth, Career, Age, Height, And More
Dlnet Deltanet
York Racecourse | Racecourses.net
Turning Obsidian into My Perfect Writing App – The Sweet Setup
Access One Ummc
Latest Posts
Article information

Author: Delena Feil

Last Updated:

Views: 6008

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Delena Feil

Birthday: 1998-08-29

Address: 747 Lubowitz Run, Sidmouth, HI 90646-5543

Phone: +99513241752844

Job: Design Supervisor

Hobby: Digital arts, Lacemaking, Air sports, Running, Scouting, Shooting, Puzzles

Introduction: My name is Delena Feil, I am a clean, splendid, calm, fancy, jolly, bright, faithful person who loves writing and wants to share my knowledge and understanding with you.