0
0
Postmantesting~15 mins

Setting variables from response in Postman - Build an Automation Script

Choose your learning style9 modes available
Set environment variable from API response
Preconditions (3)
Step 1: Send a GET request to the API endpoint https://api.example.com/user/123
Step 2: Wait for the response
Step 3: In the Tests tab, write a script to extract the 'userId' field from the JSON response
Step 4: Set an environment variable named 'userId' with the extracted value
Step 5: Verify that the environment variable 'userId' is set correctly
✅ Expected Result: The environment variable 'userId' is set with the value from the response JSON's 'userId' field
Automation Requirements - Postman Tests (JavaScript)
Assertions Needed:
Assert response status code is 200
Assert response body contains 'userId'
Assert environment variable 'userId' is set and equals the response value
Best Practices:
Use pm.response.json() to parse JSON response
Use pm.environment.set() to set environment variables
Use pm.test() for assertions
Check response status before extracting data
Automated Solution
Postman
pm.test('Status code is 200', function () {
    pm.response.to.have.status(200);
});

const responseJson = pm.response.json();

pm.test('Response has userId field', function () {
    pm.expect(responseJson).to.have.property('userId');
});

const userId = responseJson.userId;
pm.environment.set('userId', userId);

pm.test('Environment variable userId is set correctly', function () {
    const envUserId = pm.environment.get('userId');
    pm.expect(envUserId).to.eql(userId);
});

This script first checks that the response status code is 200 to ensure the request succeeded.

Then it parses the JSON response using pm.response.json().

It asserts that the response contains the userId property.

Next, it extracts the userId value and sets it as an environment variable using pm.environment.set().

Finally, it verifies that the environment variable was set correctly by comparing it to the extracted value.

This approach ensures the variable is only set if the response is valid and contains the expected data.

Common Mistakes - 3 Pitfalls
Not checking response status before extracting data
{'mistake': 'Using pm.variables.set() instead of pm.environment.set() for environment variables', 'why_bad': "pm.variables.set() sets variables only for the current request scope, not environment scope, so the variable won't persist.", 'correct_approach': 'Use pm.environment.set() to set environment variables that persist across requests.'}
Not verifying that the response contains the expected property before setting variable
Bonus Challenge

Now add data-driven testing by setting variables from three different API endpoints with different user IDs

Show Hint