Postman Tutorial Part 50 – How to Retrieve Request Body in Postman

As a part of Postman Tutorial – End to End , in this post, we will learn “How to retrieve request body in Postman?”.

Verification is the purpose of testing. Suppose we need to create a booking and we pass required details like first name, last name, check in date, check out date etc. After booking we must need to verify if booking is done for passed data.

In Postman, we may require to fetch request data to assert with response data. For example:- Create Booking API requires a request body with below details like:-

{
     "firstname" : "Jim",
     "lastname" : "Brown",
     "totalprice" : 111,
     "depositpaid" : true,
     "bookingdates" : {
         "checkin" : "2020-01-01",
         "checkout" : "2021-01-01"
     },
     "additionalneeds" : "Breakfast"
 }

And after hitting, we get below Response:-

{
    "bookingid": 13,
    "booking": {
        "firstname": "Jim",
        "lastname": "Brown",
        "totalprice": 111,
        "depositpaid": true,
        "bookingdates": {
            "checkin": "2020-01-01",
            "checkout": "2021-01-01"
        },
        "additionalneeds": "Breakfast"
    }
}
 

Now we must cross verify details passed in request body are same as in response body.

We can get request JSON body in two ways:-

  1. var jsonReq = JSON.parse(pm.request.body.raw);
  2. var jsonReq1 = JSON.parse(request.data);

Now we can write json path to extract value and do all assertions.

Complete example is below:-

// "raw" gives string. So need to parse in to JSON
var jsonReq = JSON.parse(pm.request.body.raw);
var jsonRes = pm.response.json();


pm.test("Validate booking data with passed data in request body", function () {
    pm.expect(jsonReq.firstname).to.eql(jsonRes.booking.firstname);
    pm.expect(jsonReq.lastname).to.eql(jsonRes.booking.lastname);
    pm.expect(jsonReq.totalprice).to.eql(jsonRes.booking.totalprice);
    pm.expect(jsonReq.depositpaid).to.eql(jsonRes.booking.depositpaid);
    pm.expect(jsonReq.bookingdates.checkin).to.eql(jsonRes.booking.bookingdates.checkin);
    pm.expect(jsonReq.bookingdates.checkout).to.eql(jsonRes.booking.bookingdates.checkout);
    pm.expect(jsonReq.additionalneeds).to.eql(jsonRes.booking.additionalneeds);
});


// You can also get request body using below 
var jsonReq1 = JSON.parse(request.data);
console.log(jsonReq1.firstname)

You can import example collection from here.

You can find all Selenium related post here.
You can find all API manual and automation related posts here.
You can find frequently asked Java Programs here.

1 thought on “Postman Tutorial Part 50 – How to Retrieve Request Body in Postman

Leave a Reply

Your email address will not be published. Required fields are marked *