Test Overview
This test sends an API request and sets a Postman environment variable from the JSON response. It verifies that the variable is correctly set for later use.
Jump into concepts and practice - no test required
This test sends an API request and sets a Postman environment variable from the JSON response. It verifies that the variable is correctly set for later use.
pm.test("Set variable from response", function () { const jsonData = pm.response.json(); pm.environment.set("userId", jsonData.id); pm.expect(pm.environment.get("userId")).to.eql(jsonData.id); });
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts and sends API request | Postman sends HTTP request to the API endpoint | — | PASS |
| 2 | Receives JSON response with user data | Response body contains JSON like {"id": 123, "name": "John"} | — | PASS |
| 3 | Extracts 'id' from response JSON and sets environment variable 'userId' | Environment variable 'userId' is set to 123 | Check environment variable 'userId' equals response 'id' | PASS |
| 4 | Assertion verifies 'userId' variable matches response 'id' | Variable 'userId' value is 123, matching response | pm.expect(pm.environment.get("userId")).to.eql(jsonData.id); | PASS |
token from a JSON response field auth.token?pm.environment.set(name, value) to set environment variables.pm.response.json() parses JSON; access nested field with .auth.token.userId after execution?const jsonData = pm.response.json();
pm.environment.set('userId', jsonData.data[0].id);{"data": [{"id": 42, "name": "Alice"}, {"id": 43, "name": "Bob"}]}jsonData.data[0].id accesses the first object's id, which is 42.pm.globals.set('sessionId', pm.response.headers.get('Session-ID'));get() returns null.pm.response.headers.get('Session-ID') returns null, the variable is set to null or empty, appearing unset.authToken from a nested JSON response where the token may sometimes be missing. Which script correctly sets authToken to the token value if present, or to an empty string if missing??. safely accesses nested properties without error if missing.?? to set empty string if token is undefined or nullauthToken is never undefined, avoiding test failures.pm.collectionVariables.set('authToken', token); stores the value correctly.