0
0
PostmanHow-ToBeginner ยท 3 min read

How to Set Variable from Response in Postman

In Postman, you can set a variable from a response by using the pm.variables.set() or pm.environment.set() function inside the Tests tab. Extract the value from the response using pm.response.json() or other response methods, then assign it to a variable with these functions.
๐Ÿ“

Syntax

Use the following syntax inside the Tests tab after receiving the response:

  • const jsonData = pm.response.json(); - Parses the response body as JSON.
  • pm.variables.set('variableName', value); - Sets a local variable for the current request.
  • pm.environment.set('variableName', value); - Sets an environment variable accessible across requests in the environment.
  • pm.collectionVariables.set('variableName', value); - Sets a collection variable accessible across the collection.

Choose the variable scope based on your needs.

javascript
const jsonData = pm.response.json();
pm.environment.set('variableName', jsonData.key);
๐Ÿ’ป

Example

This example shows how to extract a user ID from a JSON response and save it as an environment variable named userId. You can then use {{userId}} in subsequent requests.

javascript
const jsonData = pm.response.json();
pm.environment.set('userId', jsonData.user.id);

pm.test('User ID is set', function () {
    pm.expect(pm.environment.get('userId')).to.eql(jsonData.user.id);
});
Output
PASS User ID is set
โš ๏ธ

Common Pitfalls

1. Not parsing the response correctly: Trying to access JSON properties without parsing the response with pm.response.json() causes errors.

2. Using wrong variable scope: Setting a variable with pm.variables.set() only lasts for the current request, so it won't be available in other requests.

3. Typo in variable names: Variable names are case-sensitive and must match exactly when used.

javascript
/* Wrong: Trying to access JSON without parsing */
const userId = pm.response.user.id; // Error

/* Right: Parse JSON first */
const jsonData = pm.response.json();
const userId = jsonData.user.id;
pm.environment.set('userId', userId);
๐Ÿ“Š

Quick Reference

FunctionPurposeScope
pm.variables.set('name', value)Set variable for current request onlyLocal
pm.environment.set('name', value)Set variable for current environmentEnvironment
pm.collectionVariables.set('name', value)Set variable for entire collectionCollection
pm.globals.set('name', value)Set global variable accessible everywhereGlobal
โœ…

Key Takeaways

Use pm.response.json() to parse JSON response before extracting values.
Set variables with pm.environment.set() to reuse them across requests in the same environment.
Variable names are case-sensitive and must be consistent.
Choose the correct variable scope based on where you need to use the variable.
Always verify variable is set by adding a test assertion.