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:
Different script syntaxes exist to set or get variables for each scope in the Postman.
The syntax to set and get variables based on each scope is as follows:
set: pm.global.set('variable_key', 'variable_value')
get: pm.global.get('variable_key', 'variable_value')
set: pm.environment.set('variable_key', 'variable_value')
get: pm.environment.get('variable_key', 'variable_value')
set: pm.collectionVariables.set('variable_key', 'variable_value')
get: pm.collectionVariables.get('variable_key', 'variable_value')
set: pm.variables.set('variable_key', 'variable_value')
get: pm.variables.get('variable_key', 'variable_value')
To test out the functionality, do the following:
Open a new collection on the Postman, right-click the "Collections" tab, and select the "Add request" option.
On the new request tab, add https://postman-echo.com/get?var={{username}}
, where username is the variable to set or get a value.
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’);
Send the GET request; the response should display the value for the variable username set in the pre-request script.
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
.
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.
Free Resources