Skip to content

Instantly share code, notes, and snippets.

@sdnts
Last active January 10, 2023 20:50
Show Gist options
  • Save sdnts/b57985b0649d3407a7aa9de1bd327990 to your computer and use it in GitHub Desktop.
Save sdnts/b57985b0649d3407a7aa9de1bd327990 to your computer and use it in GitHub Desktop.
Postman pm.sendRequest example

To send a request via the sandbox, you can use pm.sendRequest.

pm.test("Status code is 200", function () {
    pm.sendRequest('https://postman-echo.com/get', function (err, res) {
        pm.expect(err).to.not.be.ok;
        pm.expect(res).to.have.property('code', 200);
        pm.expect(res).to.have.property('status', 'OK');
    });
});

Without additional options, this will sent a GET request to the URL specified. If you prefer to be more explicit, you can use the complete syntax:

pm.sendRequest({
    url: 'https://postman-echo.com/post',
    method: 'POST',
    header: 'headername1:value1',
    body: {
        mode: 'raw',
        raw: JSON.stringify({ key: "this is json" })
    }
}, function (err, res) {
    console.log(res);
});
@lflucasferreira
Copy link

Hi everyone!

I would like to know if there is a solution to my problem, let me explain it:

I am using the pm.sendRequest and I would like to send params that are stored in an array called ids. But I did not find throughout the web how to accomplish that. I tried another way and it is working but not as desired, have a look:

This code works but send multiple DELETE requests

First it retrieves all course ID and stores them in an array. After that, for each course ID, it sends multiple DELETE requests.

const URL = pm.environment.get('base_url'), TOKEN = pm.environment.get('admin_token');

// Get All Courses
pm.sendRequest({
    url: `${URL}/content-manager/explorer/application::course.course`,
    method: 'GET',
    header: {
        'Authorization': `Bearer ${TOKEN}`
    }
}, function(err, res){
    let response = res.json(), ids = _.map(response, ({ id }) => ( id ));

    // Delete Courses
    if (typeof ids !== 'undefined' && ids.length > 0) {
        _.forEach(ids, (id, index) => {
            pm.sendRequest({
                url: `${URL}/content-manager/explorer/deleteAll/application::course.course?${index++}=${id}`,
                method: 'DELETE',
                header: {
                    'Authorization': `Bearer ${TOKEN}`
                }
            }, function(err, res){
                pm.test('Code is 200'), function() {
                    pm.expect(responseBody.code).to.be.equal(200);
                }
            });
        });
    }
});

As you could see, I am looping through each ID and sending a DELETE request. But I can send multiple params in just one request, like ...course.course?0=id1&1=id2&.... For this, I can use the following code in one request:

This code is placed in the Postman Pre-request Script

Postman Delete Request

Backing up the code in case image fails

const URL = pm.environment.get('base_url'), TOKEN = pm.environment.get('admin_token');

// Get All Courses
result = pm.sendRequest({
    url: `${URL}/content-manager/explorer/application::course.course`,
    method: 'GET',
    header: {
        'Authorization': `Bearer ${TOKEN}`
    }
}, function(err, res){
    let response = res.json(), ids = _.map(response, ({ id }) => ( id ));
    _.forEach(ids, (id, index) => {
        pm.request.url.addQueryParams(`${index++}=${id}`);
    });
});

Question

How can I move the following block to the first example to make just one DELETE request? I mean, I want to use an alternative to pm.request.url.addQueryParams() to the pm.sendRequest() within it.

_.forEach(ids, (id, index) => {
    pm.request.url.addQueryParams(`${index++}=${id}`);
});

By the way, the array structure is simple: [1, 2, 3, ...], the index is autogenerated by the loop.

@RadwaSaleh
Copy link

disabled: false

are keys by default disabled?

@Andrielson
Copy link

urlencoded: [
{key: "grant_type", value: "password", disabled: false},
{key: "username", value: pm.environment.get("OAUTH_USERNAME"), disabled: false},
{key: "password", value: pm.environment.get("OAUTH_PASSWORD"), disabled: false}
]

It works like a charm! Thank you!

@joshuamiron
Copy link

I need help
I cant create script for Postman for upload file. How to write it below in body POST method:

------WebKitFormBoundaryN0hjop6xtHvXoqOv
Content-Disposition: form-data; name="_method"
PUT
------WebKitFormBoundaryN0hjop6xtHvXoqOv
Content-Disposition: form-data; name="banner_tmp_image_file"; filename="завантаження.jpeg"
Content-Type: image/jpeg
------WebKitFormBoundaryN0hjop6xtHvXoqOv--

==============My script========================================
pm.sendRequest({
url: 'http://'+pm.variables.get("pageID")+'/banner',

method: 'POST',
header: 'Content-Type:multipart/form-data; boundary=----WebKitFormBoundary' + random(16),
body: {
mode: 'fromData',
formData: [
{
_method: "PUT",
background_tmp_image_file: ('C:\Users\Desktop\1.jpeg')
}
]
}
}, function (err, res) {
console.log(res);
});

This one has a typo - it says "mode: 'fromData'. Should be 'formData'.

@Kyogre
Copy link

Kyogre commented Apr 24, 2021

Pre-req script example of how to perform POST request before performing GET request

Example task:
I have POST request that returns response like "/chargesresponse/some-uid-numbers", and I have GET request which I want to parse mentioned POST request's answer to it's URL. So I need to make POST-request, then add it's response to GET-request URL.

Example solution achieved via variable in URL and pre-req script:
GET https://mydomain-for-getting-charges-list.com/my-sub-path{{myVariable123}}?exampleParameter1=true&exampleParameter2=true

Pre-request script:

const myChargesrequestScript = {
    url: 'https://mydomain-for-getting-charges-list.com/my-sub-path/chargesrequest',
    method: 'POST',
    header: {
        'Content-Type': 'application/json',
        'Authorization': 'Basic abcde123=='
        },
    body: {
    mode: 'raw',
    raw: JSON.stringify({
    "msgUID": "parameter123",
    "senderName": "DBO3",
    "payerIdList": [
       {
           "idType": "UIN",
           "idNumber": "123456789"
       }
   ],
    "chargeType": "ALL"
})
}
};
pm.sendRequest(myChargesrequestScript,function (err, response) {
    pm.collectionVariables.set ("myVariable123", response.text());
    });

Tests script example of how to parse field value from POST response body

We have some POST request that returns response with many fields, e.g.:

{
    "field1": "123"
    "field2": "456"
}

These fields have string values between the quotes.

And we have GET request like "https://someurl.com/value of field1"

The example task is to automate parsing value of field1 from POST's response to GET's url.
To do so we need to write such Test in POST's request:

var jsonData = JSON.parse(responseBody);
var parsed_field1 = jsonData.field1;
pm.collectionVariables.set ("field1_for_get", parsed_field1);

As you see, jsonData.field1 is the most important part of the script.

Thus remains only write the variable into the url of GET request: https://someurl.com/{{field1_for_get}}

Now you can perform POST request, then perform GET request, and GET request will have parsed field1 value automatically, so you will perform 2 steps with just a 3 clicks of a mouse.

@timohuovinen
Copy link

timohuovinen commented May 7, 2021

I've mentioned my solution here:
postmanlabs/postman-app-support#4404

I've worked around logging in with oAuth2 in the following way

utils = {
    login: function(pm, username, password) {
        let access_token = pm.collectionVariables.get("access_token");

        // logic to check expiration not included in this example
        if (isExpired(access_token)) {
            pm.sendRequest({
                url: pm.environment.get("auth") + "/token",
                method: 'POST',
                header: {
                    'accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: {
                    mode: 'urlencoded',
                    urlencoded:
                        [
                            { key: "client_id", value: pm.environment.get("client_id") },
                            { key: "client_secret", value: pm.environment.get("client_secret") },
                            { key: "username", value: username },
                            { key: "password", value: password },
                            { key: "grant_type", value: "password" },
                        ]
                }
            }, (err, res) => {
                if (err !== null) {
                    console.error(err);
                    return;
                }
                let responseJson = res.json();
                pm.collectionVariables.set("access_token", responseJson.access_token);
            });
        }
    }
};

and then you can call it like this

let username = pm.collectionVariables.get("username");
let password = pm.collectionVariables.get("password");
utils.login(pm, username, password);

@zeelz
Copy link

zeelz commented Sep 18, 2021

This app requires a two-step login, first to get verify domain, which gives you token to do proper username/password login. Then you get your main token for any further request on gated content.
This is my postman setup:

Pre-script

pm.sendRequest({
    url: "https://example.com/v1/auth/domain",
    method: "POST",
    header: {
        "Content-Type": "application/json"
    },
    body: {
        mode: "raw",
        raw: JSON.stringify({"key": "value"})
    }
}, (err , res) => {
    let {data: {token}} = res.json();
    pm.environment.set("domain_token",token);
})

Main Request

[Headers Tab]
Authorization: Bearer {{domain_token}}
Note: {domain_token} was set by pre-script

[Body tab]
{
"email": "email",
"password": "password"
}

Post-script (Tests)
let {data: {token}} = JSON.parse(responseBody);
pm.environment.set("access_token",token);

From this point any request can make use of the {access_token} from the environment.

I want to improve it with refresh token so that my login persists for as long as refresh allows. Suggestions are welcome.

@arun-a-nayagam
Copy link

arun-a-nayagam commented Sep 22, 2021

Hi,
I have a situation where I need to make a REST call from inside the "Tests" tab.

var jsonData = pm.response.json();

async function getApp(uuid) {
    console.log(uuid);
    pm.sendRequest({
        url: pm.environment.get(base_url)+'/api-management/1.0/applications/'+uuid,
        method: 'GET',
        header: {
            'Accept': 'application/json',
            'Authorization': pm.environment.get("accessToken")
        }
    }, function (err, res) {
        console.log(res.json());
    });
}

pm.test("APPs", function () {
    _.each(jsonData.results, (item) => {
        var name = item.name.toLowerCase().replace(/\s/g, "_");
        pm.environment.set("app_"+name+"_uuid", item.uuid);
        getApp(item.uuid);
    })
});

So, within pm.test I am calling another function called "getApp", that's making a pm.sendRequest call.
For some reason that pm.sendRequest is not getting executed. Note the console.log(uuid) is getting printed fine.
Can you please help identify the issue?

@jprealini
Copy link

jprealini commented Oct 6, 2021

@arun-a-nayagam I have seen stuff like that happen because the "pm.test" block finishes executing before the rest call is completed... I haven't found any other way to solve that but using setTimeout... I would try putting a timeout probably in the getApp call

setTimeout(() => { getApp(item.uuid ) },2000)

And see what that does... or maybe around the whole pm.test

setTimeout(() => {
pm.test("Apps", function () {
...
})
) },2000)

EDIT: I came back here because for some reason your issue kept revolving inside my head, and found a few things I think need to be pointed out

  1. Why are you setting up the environment variable inside the pm.test block? I mean, the pm.test block is intended for testing your request's response...
  2. Why is it that you are not asserting anything in your test?
  3. How exactly are you trying to detect that the sendrequest has been executed? By checking if the console.log prints correctly?

@arun-a-nayagam
Copy link

Hi,
@jprealini Thank you for the reply. Apologies, I did find what my issue was but I forgot to come and update here.
Basically, I had to surround my pm.sendRequest around a try, catch block.
If it's not surrounded then it was not writing to the console of an issue with the sendRequest.

And about your questions,

  1. In this instance I don't use the Test block for asserting a test case.
    My intention is to run a script after a postman request to initialize my env vars which I will subsequently use in other API calls.
  2. See 1
  3. Yes, I was expecting the console.log to indicate what the response was.
    But as I said there was an issue with the call and without try/catch there was no information shown in the console.

I really appreciate you replying back and checking! Thank you.

@kiranparajuli589
Copy link

Is there any way to run a saved request from the collection in the Pre-request Script?

like postman.setNextRequest('req-name') but before the actual request not after.

@abeward
Copy link

abeward commented Jan 7, 2022

Is there any way to run a saved request from the collection in the Pre-request Script?

Not that I'm aware of. I've recently asked them for this feature, though. It would be a huge timesaver if we could just pm.sendRequest by GUID.

@brendan-robert
Copy link

any update on this? @ABlomberg

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment