0
0
PostmanHow-ToBeginner ยท 3 min read

How to Use pm.globals.set in Postman for Global Variables

Use pm.globals.set('variableName', 'value') in Postman scripts to create or update a global variable accessible across all requests. This helps share data like tokens or IDs throughout your collection.
๐Ÿ“

Syntax

The pm.globals.set function takes two arguments: the name of the global variable as a string, and the value you want to assign to it. This sets or updates the global variable for use in any request or script within Postman.

javascript
pm.globals.set('variableName', 'value');
๐Ÿ’ป

Example

This example shows how to save an authentication token as a global variable after a login request. You can then use this token in other requests by referencing the global variable.

javascript
pm.test('Save auth token globally', () => {
    const jsonData = pm.response.json();
    pm.globals.set('authToken', jsonData.token);
    pm.expect(jsonData.token).to.exist;
});
Output
Test passed: Save auth token globally
โš ๏ธ

Common Pitfalls

  • Forgetting to use quotes around the variable name causes syntax errors.
  • Setting a global variable with pm.globals.set overwrites any existing variable with the same name.
  • Using global variables without clearing them can cause stale data issues.
  • Confusing pm.globals.set with environment or collection variables; globals are shared across all collections.
javascript
/* Wrong: missing quotes around variable name */
pm.globals.set(authToken, '12345');

/* Right: quotes around variable name */
pm.globals.set('authToken', '12345');
๐Ÿ“Š

Quick Reference

FunctionDescriptionExample
pm.globals.set(name, value)Sets or updates a global variablepm.globals.set('token', 'abc123');
pm.globals.get(name)Retrieves a global variable's valueconst token = pm.globals.get('token');
pm.globals.unset(name)Removes a global variablepm.globals.unset('token');
pm.globals.clear()Clears all global variablespm.globals.clear();
โœ…

Key Takeaways

Use pm.globals.set('name', 'value') to create or update global variables in Postman.
Global variables set with pm.globals.set are accessible across all requests and collections.
Always use quotes around the variable name to avoid syntax errors.
Clear or unset global variables when no longer needed to prevent stale data.
Remember that global variables differ from environment and collection variables.