How to extract parameters from the request body in Postman Tests?
In Postman, using pm.request.body object makes it easy to extract parameters from the request body. Through example test scripts, you can parse the request body and extract parameters, such as extracting the value of a field named 'name'.
If you want to extract parameters from the request body in Postman, you can use the pm.request.body
object. Here's an example demonstrating how to extract parameters from the request body in Postman Tests:
1.Example Request Body Parameters
Assuming your interface's request body looks like this:
{
"name": "John Doe",
}
![extract parameters from the request body in Postman Tests](https://zguyun.com/content/images/2024/02/data-src-image-b9ea93c7-0638-4bbe-8ba7-a4140cc21610.png)
2.Extracting Request Body Parameters
If you want to extract the value of the 'name' field in Postman, you can use the following test script to extract the 'name' parameter:
// Parse the request body
var body = JSON.parse(pm.request.body.raw);
// Extract the parameter
var name = body.name;
// Output the parameter to the console
console.log("Name: " + name);
// Store the parameter in environment variables (optional)
pm.environment.set("name", name);
In this example, we used pm.request.body.raw
to get the original body of the request, then parsed it into JSON format to extract the 'name' parameter. You can perform any testing operations you desire on these parameters according to your needs. If you wish to use these parameters in other requests, you can store them in environment variables for access to other requests.
![extract parameters from the request body in Postman Tests](https://zguyun.com/content/images/2024/02/data-src-image-566c812d-45c1-4981-b325-b2aca73a398d.png)
Summary
In Postman, using pm.request.body
object makes it easy to extract parameters from the request body. Through example test scripts, you can parse the request body and extract parameters, such as extracting the value of a field named 'name'. Additionally, you can store the extracted parameters in environment variables for access in other requests.
![](https://zguyun.com/content/images/2024/02/data-src-image-b9ea93c7-0638-4bbe-8ba7-a4140cc21610.png)
Reference:
Learn more:
- Introduction to Using Request Headers in Postman
- The differences between form-data, x-www-form-urlencoded, raw, binary, and GraphQL in Postman's Body
Learn more: