How to return a sendRequest response?

I set my methods as environment variables. Here is an example:

var getEventCategory = (name,callback) => {
       return pm.sendRequest({
            url: pm.environment.get("mainUrl") + "/event-category/" + name,
            method: 'GET',
            header: {
                'content-type': 'application/json',
                'Authorization': "Bearer " + pm.environment.get("accessToken"),
                'Accept': "*/*"
            }

        }, function(err, res) {
            if (callback) {
                callback();
            }
        });
    }

I want to return response code and body from this request when I call them in my scripts. How can I do that? What does pm.sendRequest actually return?

Hi there @batuarslan -

The docs include some examples of using sendRequest(), along with a link to the response structure reference.

You can also log the response (res in your example) in the Postman console to inspect the response, and access the code like res.code.

2 Likes

Hey,

Just adding some additional info around getting the response body, as it’s a little bit different because you need to convert that stream object.

If you add something like this, under the console.log() lines from @joyce’s image above, you should also be able to log out the body of that request.

let resBody = new Buffer.from(res.stream).toString()
console.log(JSON.parse(resBody))

This is just one way of doing it but I’m sure that there are many more. :slight_smile:

1 Like

res has json and text methods, so you can get the response JSON/text for example via:

var json = res.json()
var text = res.text()

4 Likes

Awesome!! Thanks @matt I knew there was a simple way of getting that rather than the long winded way I add. :grin:

Hopefully, that’s all @batuarslan needs now to complete the task :heart:

1 Like