How to extract parameters from the response body in Postman Tests?

In Postman, using JavaScript to write test scripts can extract parameters from the response body. By parsing the JSON-formatted response body, you can easily extract the required parameters and optionally store them in environment variables for use in other requests.

Home > Blog > How to extract parameters from the response body in Postman Tests?

In Postman, you can use JavaScript to write test scripts to extract parameters from the response body. Here is a simple example demonstrating how to extract parameters from the response body in JSON format.

1.Example Response Body Parameters

After making a request in Postman, suppose the response body returned by the API request is as follows:

{
    "code": "0",
    "data": {
        "name": "Margaret"
    },
    "message": "success"
}

2.Extracting Response Body Parameters

If you want to extract the name field from the data object, you can use the following test script to extract the name parameter:

// Parse the response body
var body = JSON.parse(responseBody);

// Extract parameters
var name = body.data.name;

// Output parameters to console
console.log("Name: " + name);

// Store parameters in environment variables (optional)
postman.setEnvironmentVariable("name", name);

In this example, responseBody is a predefined variable in Postman, representing the response body of the current request. We first parse the JSON-formatted response body and then extract the name parameter. You can perform any testing operations you want on these parameters according to your requirements, such as checking if their values meet expectations. If you want to use these parameters in other requests, you can store them in environment variables for access to other requests.

extract parameters from the response body in Postman Tests

Summary

In Postman, using JavaScript to write test scripts can extract parameters from the response body. By parsing the JSON-formatted response body, you can easily extract the required parameters and optionally store them in environment variables for use in other requests.

How to extract parameters from the response body in Postman Tests?
In Postman, using JavaScript to write test scripts can extract parameters from the response body. By parsing the JSON-formatted response body, you can easily extract the required parameters and optionally store them in environment variables for use in other requests.

Reference:

Learn more: