We extract data from responses to use it in later tests or requests. This helps us check if the system works correctly step-by-step.
0
0
Extracting data from responses in Postman
Introduction
When you want to save a user ID from a login response to use in another request.
When you need to get a token from a response to authorize future requests.
When you want to check if a specific value appears in the response data.
When you want to pass data dynamically between multiple API calls in a test collection.
Syntax
Postman
pm.test("Extract value from response", function () { var jsonData = pm.response.json(); pm.environment.set("keyName", jsonData.data.id); });
Use pm.response.json() to parse the response body as JSON.
Use pm.environment.set("key", value) to save data for later use.
Examples
This saves the
token from the response into an environment variable called userToken.Postman
pm.test("Save user token", function () { var jsonData = pm.response.json(); pm.environment.set("userToken", jsonData.token); });
This saves the
order.id into a collection variable named orderId.Postman
pm.test("Extract order ID", function () { var jsonData = pm.response.json(); pm.collectionVariables.set("orderId", jsonData.order.id); });
This checks if the response status code is 200 (OK).
Postman
pm.test("Check response status", function () { pm.response.to.have.status(200); });
Sample Program
This test extracts the user.id from the JSON response and saves it as an environment variable userID. It also checks that the ID is a number.
Postman
pm.test("Extract user ID from response", function () { var jsonData = pm.response.json(); pm.environment.set("userID", jsonData.user.id); pm.expect(jsonData.user.id).to.be.a('number'); });
OutputSuccess
Important Notes
Always check the response format before extracting data to avoid errors.
Use environment or collection variables to share data between requests.
Use descriptive variable names to keep your tests clear.
Summary
Extracting data helps connect multiple API requests in tests.
Use pm.response.json() to read JSON responses.
Save data with pm.environment.set() or pm.collectionVariables.set().