Getting started with Scripting in the Postman
Last Updated :
23 Jul, 2025
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:
- 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.
- 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.
- 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.
- 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:
- 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.
- 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:
- 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.
- 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.
- 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.
- 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({
url: 'https://api.example.com/some-endpoint',
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.

Similar Reads
Software Testing Tutorial Software testing is an important part of the software development lifecycle that involves verifying and validating whether a software application works as expected. It ensures reliable, correct, secure, and high-performing software across web, mobile applications, cloud, and CI/CD pipelines in DevOp
10 min read
What is Software Testing? Software testing is an important process in the Software Development Lifecycle(SDLC). It involves verifying and validating that a Software Application is free of bugs, meets the technical requirements set by its Design and Development, and satisfies user requirements efficiently and effectively.Here
11 min read
Principles of Software testing - Software Testing Software testing is an important aspect of software development, ensuring that applications function correctly and meet user expectations. From test planning to execution, analysis and understanding these principles help testers in creating a more structured and focused approach to software testing,
3 min read
Software Development Life Cycle (SDLC) Software Development Life Cycle (SDLC) is a structured process that is used to design, develop, and test high-quality software. SDLC, or software development life cycle, is a methodology that defines the entire procedure of software development step-by-step. The goal of the SDLC life cycle model is
8 min read
Software Testing Life Cycle (STLC) The Software Testing Life Cycle (STLC) is a process that verifies whether the Software Quality meets the expectations or not. STLC is an important process that provides a simple approach to testing through the step-by-step process, which we are discussing here. Software Testing Life Cycle (STLC) is
7 min read
Types of Software Testing Software testing is a important aspect of software development life-cycle that ensures a product works correctly, meets user expectations, and is free of bugs. There are different types of software testing, each designed to validate specific aspects of an application, such as functionality, performa
15+ min read
Levels of Software Testing Software Testing is an important part of the Software Development Life Cycle which is help to verify the product is working as expected or not. In SDLC, we used different levels of testing to find bugs and errors. Here we are learning those Levels of Testing in detail.Table of ContentWhat Are the Le
4 min read
Test Maturity Model - Software Testing The Test Maturity Model (TMM) in software testing is a framework for assessing the software testing process to improve it. It is based on the Capability Maturity Model(CMM). It was first produced by the Illinois Institute of Technology to assess the maturity of the test processes and to provide targ
8 min read
SDLC MODELS
TYPES OF TESTING