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
| Method | Description | Example |
|---|---|---|
| pm.environment.set | Sets or updates an environment variable | pm.environment.set('key', 'value'); |
| pm.environment.get | Retrieves an environment variable's value | pm.environment.get('key'); |
| pm.environment.unset | Removes an environment variable | pm.environment.unset('key'); |
| pm.environment.clear | Clears all environment variables | pm.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.