Set environment variable from API response
Preconditions (3)
✅ Expected Result: The environment variable 'userId' is set with the value from the response JSON's 'userId' field
Jump into concepts and practice - no test required
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.
Now add data-driven testing by setting variables from three different API endpoints with different user IDs
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.