0
0
Postmantesting~5 mins

Setting variables from response in Postman

Choose your learning style9 modes available
Introduction

We set variables from a response to save important data for later use in tests or requests. This helps us reuse values without typing them again.

When you want to save a user ID returned after creating a user to use in later requests.
When you need to store an authentication token from a login response for future API calls.
When you want to capture a dynamic value like a timestamp or session ID from a response.
When you want to verify a value in the response and keep it for comparison in another test.
When you want to chain multiple API requests that depend on data from previous responses.
Syntax
Postman
pm.environment.set("variable_name", value);
pm.globals.set("variable_name", value);
pm.collectionVariables.set("variable_name", value);

Use pm.environment.set to save variables in the current environment.

Use pm.globals.set to save variables globally across all environments.

Examples
This saves the id from the JSON response into an environment variable called userId.
Postman
let jsonData = pm.response.json();
pm.environment.set("userId", jsonData.id);
This saves the Authorization header value into a global variable authToken.
Postman
let token = pm.response.headers.get("Authorization");
pm.globals.set("authToken", token);
This saves a nested value session.id from the response into a collection variable sessionId.
Postman
let jsonData = pm.response.json();
pm.collectionVariables.set("sessionId", jsonData.session.id);
Sample Program

This test script saves the user.id from the response into an environment variable userId. It also checks that the user ID is a number and the user name is "Alice".

Postman
pm.test("Save user ID from response", function () {
    let jsonData = pm.response.json();
    pm.environment.set("userId", jsonData.user.id);
    pm.expect(jsonData.user.id).to.be.a('number');
});

pm.test("Check user name", function () {
    let jsonData = pm.response.json();
    pm.expect(jsonData.user.name).to.eql("Alice");
});
OutputSuccess
Important Notes

Always check that the response contains the data before setting variables to avoid errors.

Use meaningful variable names to keep your tests clear and easy to understand.

Remember environment variables are specific to the selected environment in Postman.

Summary

Setting variables from response helps reuse data across requests and tests.

Use pm.environment.set, pm.globals.set, or pm.collectionVariables.set depending on scope.

Extract values from JSON or headers and save them for later use.