How to set and get variables through scripting in Postman

Key-value pairs represent variables in Postman. We can use them to pass data values between environments, requests, parameters, collections, and scripts.

Variables exist in different scopes, such as "Global," "Environment," "Collection," and "Local" as represented in the illustration below:

Scope hierarchy
Scope hierarchy

Different script syntaxes exist to set or get variables for each scope in the Postman.

Syntax

The syntax to set and get variables based on each scope is as follows:

Global

set: pm.global.set('variable_key', 'variable_value')

get: pm.global.get('variable_key', 'variable_value')

Environment

set: pm.environment.set('variable_key', 'variable_value')

get: pm.environment.get('variable_key', 'variable_value')

Collection

set: pm.collectionVariables.set('variable_key', 'variable_value')

get: pm.collectionVariables.get('variable_key', 'variable_value')

Local

set: pm.variables.set('variable_key', 'variable_value')

get: pm.variables.get('variable_key', 'variable_value')

Example

To test out the functionality, do the following:

  1. Open a new collection on the Postman, right-click the "Collections" tab, and select the "Add request" option.

Click on Add request option
Click on Add request option
  1. On the new request tab, add https://postman-echo.com/get?var={{username}}, where username is the variable to set or get a value.

Add the request URL and set the method type
Add the request URL and set the method type
  1. Go to the "Pre-request Script" section within the "Request" tab and add the following scripts to set a value and get a value on a collection variable:
    pm.collectionVariables.set(‘username’, ‘davidadediji’);
    pm.collectionVariables.get(‘username’);

Enter the script in the "Pre-request Script" tab on Postman's editor body
Enter the script in the "Pre-request Script" tab on Postman's editor body
  1. Send the GET request; the response should display the value for the variable username set in the pre-request script.

Click on the send button to send the request and run the script.
Click on the send button to send the request and run the script.
  1. In addition, the value for the script get functionality can be saved in a new variable, which we can display on the console using console.log.

View the output of the request and script through the response body and console
View the output of the request and script through the response body and console

This is how we can set and get variables through scripts in Postman. We can use the Postman application below to test everything we've learned.

Try it out the commands above

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved