0
0
PostmanHow-ToBeginner ยท 3 min read

How to Use pm.environment.set in Postman for Environment Variables

Use pm.environment.set('variableName', value) in Postman scripts to create or update an environment variable. This lets you store data dynamically during your API tests for reuse in later requests.
๐Ÿ“

Syntax

The syntax for setting an environment variable in Postman is pm.environment.set(variableName, value).

  • variableName: The name of the environment variable as a string.
  • value: The value you want to assign to this variable. It can be a string, number, or any serializable data.

This command updates the environment variable if it exists or creates it if it does not.

javascript
pm.environment.set('token', '12345abcde');
๐Ÿ’ป

Example

This example shows how to set an environment variable named authToken with a value returned from an API response. It demonstrates extracting a token from JSON and saving it for later use.

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

Common Pitfalls

Common mistakes when using pm.environment.set include:

  • Trying to set variables outside of script contexts like Pre-request or Tests tab.
  • Using incorrect variable names without quotes, causing syntax errors.
  • Not checking if the response data exists before setting variables, leading to undefined values.
  • Confusing environment variables with global or collection variables.

Always ensure your script runs after the response is received and that variable names are strings.

javascript
/* Wrong way: missing quotes around variable name */
pm.environment.set(authToken, 'value');

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

Quick Reference

MethodDescriptionExample
pm.environment.setSets or updates an environment variablepm.environment.set('key', 'value');
pm.environment.getRetrieves an environment variable's valuepm.environment.get('key');
pm.environment.unsetRemoves an environment variablepm.environment.unset('key');
pm.environment.clearClears all environment variablespm.environment.clear();
โœ…

Key Takeaways

Use pm.environment.set('name', value) to create or update environment variables in Postman scripts.
Always use quotes around the variable name to avoid syntax errors.
Set environment variables in the Tests or Pre-request Script tab after ensuring data exists.
Use environment variables to store dynamic data for reuse across requests.
Check your variable values with pm.environment.get to verify they are set correctly.