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.
Setting variables from response in 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.
id from the JSON response into an environment variable called userId.let jsonData = pm.response.json(); pm.environment.set("userId", jsonData.id);
Authorization header value into a global variable authToken.let token = pm.response.headers.get("Authorization"); pm.globals.set("authToken", token);
session.id from the response into a collection variable sessionId.let jsonData = pm.response.json(); pm.collectionVariables.set("sessionId", jsonData.session.id);
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".
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"); });
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.
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.