Reputation: 13
I have few need-to-have params in JSON raw data in my request body and I want to validate in the pre-request script in Postman if those params are present in the body or not.
{
"stores": [
{
"city": "Tokyo",
"name": "Church Street"
....
....
}
]
}
How to check if city
and name
is passed or not in the request body?
Upvotes: 1
Views: 4300
Reputation: 25851
You can use the pm.test
function with the pm.expect
assertions in the Pre-request Scripts
.
As Postman comes with Lodash, you can use the _.get() function in the sandbox to get the data from the stores
array. You would need to use JSON.parse()
to correctly assign the data from the request body in the _.get()
function.
let requestBody = _.get(JSON.parse(pm.request.body.raw), 'stores[0]')
pm.test("Check Body", () => {
pm.expect(requestBody).to.have.keys(['city', 'name'])
})
Or something like this without Lodash:
let requestBody = JSON.parse(pm.request.body.raw)
pm.test("Check Body", () => {
pm.expect(requestBody.stores[0]).to.have.keys(['city', 'name'])
})
More info on the pm.*
API can be found here:
https://learning.postman.com/docs/postman/scripts/postman-sandbox-api-reference/
Upvotes: 1
Reputation: 2209
Use pm.test
as you can see request body, content-type, response content in Run Results. Export Results has too many details.
Test Request Body:
pm.test(JSON.parse(pm.request.body));
Test URLEncoded with Request Body:
pm.test(JSON.stringify(pm.request.body.urlencoded.toObject(true)));
Test Raw Text in Request Body:
pm.test(JSON.parse(pm.request.body.raw));
Example:
var reqBody = request.data; //JSON.parse(request.data);
tests["Data"] = reqBody.stores[0].city !== null;
Upvotes: 0