0
0
PostmanHow-ToBeginner ยท 3 min read

How to Set Variable in Postman Script: Simple Guide

In Postman scripts, you set a variable using pm.variables.set('variableName', 'value') for local scope. To set environment or global variables, use pm.environment.set('variableName', 'value') or pm.globals.set('variableName', 'value') respectively.
๐Ÿ“

Syntax

Postman provides different scopes to set variables in scripts. The main methods are:

  • pm.variables.set('key', 'value'): Sets a variable local to the current request script.
  • pm.environment.set('key', 'value'): Sets a variable in the current environment, accessible across requests.
  • pm.globals.set('key', 'value'): Sets a global variable accessible in all environments.

Each method takes two arguments: the variable name as a string, and the value to assign.

javascript
pm.variables.set('myVar', '123');
pm.environment.set('envVar', 'abc');
pm.globals.set('globalVar', 'xyz');
๐Ÿ’ป

Example

This example shows how to set an environment variable named token after receiving it in a response, so you can use it in later requests.

javascript
pm.test('Set token variable', () => {
    const jsonData = pm.response.json();
    pm.environment.set('token', jsonData.access_token);
    pm.expect(pm.environment.get('token')).to.eql(jsonData.access_token);
});
Output
Test passed: Set token variable
โš ๏ธ

Common Pitfalls

Common mistakes when setting variables in Postman scripts include:

  • Using pm.variables.set when you want the variable to persist across requests; it only sets it locally.
  • Forgetting to set the variable in the correct scope (environment or global) depending on usage.
  • Trying to set variables before the response is received, causing undefined values.

Always ensure you set variables after the response is available and use the correct scope method.

javascript
/* Wrong: setting environment variable with pm.variables.set (won't persist) */
pm.variables.set('userId', '123');

/* Right: setting environment variable with pm.environment.set */
pm.environment.set('userId', '123');
๐Ÿ“Š

Quick Reference

MethodScopeDescription
pm.variables.set('key', 'value')LocalVariable available only in current script execution
pm.environment.set('key', 'value')EnvironmentVariable persists in current environment across requests
pm.globals.set('key', 'value')GlobalVariable persists globally across all environments and requests
โœ…

Key Takeaways

Use pm.environment.set to save variables for use across multiple requests.
pm.variables.set only sets variables locally within the current script execution.
Always set variables after the response is received to avoid undefined values.
Choose the correct scope (local, environment, global) based on how long you need the variable.
Verify variable setting by retrieving it with pm.environment.get or pm.globals.get.