How can I access Request object in PostMan
Asked Answered
B

6

33

As title, How can I access Request object in PostMan ? Is it possible to create a testcase like this

tests["Response content restaurant Id : ", req.body.restaurantId] = responseBody.has(req.body.restaurantId);
Bagwell answered 25/11, 2015 at 10:12 Comment(0)
B
61

After doing some research in Postman Sandbox

I finally found the answer for myself.

var reqBody = JSON.parse(request.data);
var resBody = JSON.parse(responseBody)
tests["Data"] = reqBody.restaurantId === resBody.restaurantId;
Bagwell answered 25/11, 2015 at 11:42 Comment(2)
var reqBody = request.data; works for me - with JSON.parse() I got an errorZenda
It depends on whether you're using the form-data or the raw JSON body to make the request @o.z. In case you never figured it out (I realize it has been some time).Reisch
L
23

If you are doing it from a test script this is the syntax:

pm.test("Update env", function () {
    var req = JSON.parse(pm.request.body.raw);
    pm.environment.set("restaurantId", req.restaurantId);

    var resp = pm.response.json();
    pm.environment.set("restaurantId", resp.restaurantId);
});
Longterm answered 28/10, 2019 at 10:37 Comment(1)
JSON.parse(pm.request.body.raw); worked for me with postman v7.35Nearly
L
5
//this works for form-data:
var reqBody = request.data;
//this works for raw:
var reqBody = JSON.parse(request.data);
Lase answered 19/9, 2019 at 21:4 Comment(0)
E
1

for application/json request body, you would use the answer provided by Trung. However, for the form data, you need to simply access the body using request.data and then you can get your variables directly, like request.data.email or request.data.password

Essence answered 7/9, 2019 at 19:31 Comment(0)
C
0

This seems to work in latest Postman version (Thanks to tom redfern comment) ->

JSON.parse(pm.request.body.raw); 
Counterman answered 27/1, 2023 at 16:47 Comment(0)
C
0

Because I was using the body as a template, using JSON.parse directly on pm.request.body.raw, wasn't working for me.

Using pm.variables.replaceIn() to resolve pm.request.body.raw did.

const body = JSON.parse( pm.variables.replaceIn(pm.request.body.raw))

Link: https://community.postman.com/t/accessing-request-data-with-filled-body-parameters-in-pre-request-script/9554/4

Cochabamba answered 11/3 at 14:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.