0
0
Postmantesting~15 mins

Saving responses in Postman - Build an Automation Script

Choose your learning style9 modes available
Save API response to environment variable
Preconditions (2)
Step 1: Open Postman and create a new GET request to 'https://jsonplaceholder.typicode.com/todos/1'
Step 2: Send the request
Step 3: In the Tests tab, write a script to save the 'title' field from the JSON response to an environment variable named 'todoTitle'
Step 4: Save the request
Step 5: Send the request again
Step 6: Verify that the environment variable 'todoTitle' is set with the value from the response
✅ Expected Result: The environment variable 'todoTitle' contains the 'title' value from the API response after the request is sent
Automation Requirements - Postman Tests (JavaScript)
Assertions Needed:
Verify response status code is 200
Verify response body contains 'title' field
Verify environment variable 'todoTitle' is set with correct value
Best Practices:
Use pm.response.json() to parse JSON response
Use pm.environment.set() to save variables
Use pm.test() for assertions
Keep test scripts clear and simple
Automated Solution
Postman
pm.test('Status code is 200', () => {
    pm.response.to.have.status(200);
});

const responseJson = pm.response.json();

pm.test('Response has title field', () => {
    pm.expect(responseJson).to.have.property('title');
});

pm.environment.set('todoTitle', responseJson.title);

pm.test('Environment variable todoTitle is set', () => {
    const savedTitle = pm.environment.get('todoTitle');
    pm.expect(savedTitle).to.eql(responseJson.title);
});

This script runs after the API response is received in Postman.

First, it checks the status code is 200 to confirm the request succeeded.

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

It asserts that the response contains a title field.

Next, it saves the title value to an environment variable called todoTitle using pm.environment.set().

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

This approach ensures the response data is saved and can be reused in other requests or tests.

Common Mistakes - 3 Pitfalls
Not parsing the response JSON before accessing fields
{'mistake': 'Using pm.variables.set() instead of pm.environment.set() when intending to save 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 save variables that persist across requests.'}
Not adding assertions to verify the response status code
Bonus Challenge

Now add data-driven testing by saving the 'title' field from three different todo items (ids 1, 2, and 3) into separate environment variables.

Show Hint