Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App

Getting started with Scripting in the Postman

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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({         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.

test-results



M

moonpatel2003
Improve
Article Tags :
  • Geeks Premier League
  • Software Testing
  • Postman
  • Geeks Premier League 2023

Similar Reads

    Postman Tutorial
    This Postman Tutorial is designed for beginners as well as professionals and covers basic and advanced concepts of the Postman Tutorial Application Programming Interface. In This Postman Tutorial, you’ll learn various important Postman Topics which are Sending API Requests, Collections, Variables, S
    5 min read

    Introduction

    How to Download and Install Postman on Windows?
    Postman is a platform for building and using APIs and helps for simplifying the steps in the APIs lifecycles to streamline collaboration for creating faster APIs. It includes various API tools to accelerate the development cycle, including the design mockups and testing documentation, etc. Postman w
    2 min read
    Sending Your First Request via Postman
    Postman is a tool that we are using for managing our APIs. It is used for sending the request to the server and then looking at the response from it. It helps us to understand the behavior of the API. Postman can help us with Performance Testing, Managing the API in one place, and sharing the collec
    4 min read
    How to Create Collections in Postman
    In this article, we will see how to create Collections in Postman. It is an Application Programming Interface (API) tool that streamlines the lifecycle of API development and testing in an efficient manner. It can be used to develop, design, document, and test APIs. Postman provides the ability to g
    2 min read

    Sending API Requests

    How to create and send GET requests in Postman?
    Postman is an API(application programming interface) development tool which helps to build, test and modify APIs. It has the ability to make various types of HTTP requests(GET, POST, PUT, PATCH), saving environments for later use, converting the API to code for various languages(like JavaScript, Pyt
    1 min read
    Postman - Working, HTTP Request & Responses
    API...Application Programming Interface... If you're a developer then this word is nothing new for you...Being a developer, you know the importance of API in any kind of application. In simple terms, API is a defined set of rules with some defined methods of communication. With the help of API, soft
    5 min read
    Postman - Working, HTTP Request & Responses
    API...Application Programming Interface... If you're a developer then this word is nothing new for you...Being a developer, you know the importance of API in any kind of application. In simple terms, API is a defined set of rules with some defined methods of communication. With the help of API, soft
    5 min read
    How to Perform POST Request in Postman with Test Validation?
    Postman is an API(application programming interface) development tool that helps to build, test, and modify APIs. Almost any functionality that could be needed by any developer is encapsulated in this tool. It is used by over 5 million developers every month to make their API development easy and si
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences