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);
});
@Sussumu
Copy link

Sussumu commented Oct 31, 2018

If you need to send x-www-form-urlencoded data, the mode and object to generate the request is urlencoded. @DannyDainton post on his blog helped me on this one!

@JenteVH
Copy link

JenteVH commented Feb 5, 2019

Is it possible to run a saved request from your workspace by name, instead of having to recreate it entirely in the pre-request script?

@d4rkd0s
Copy link

d4rkd0s commented Mar 1, 2019

Is it possible to run a saved request from your workspace by name, instead of having to recreate it entirely in the pre-request script?

👍 +1 this, same question as @JenteVH

@zeckdude
Copy link

zeckdude commented Apr 4, 2019

If anybody is looking to use an existing endpoint in your pre-request script instead of having to manually rewrite it, check out this thread: postmanlabs/postman-app-support#4193

@enedrio
Copy link

enedrio commented Aug 16, 2019

Hi,
I'm having trouble with sendRequest.
My Request looks like this:

{
    url: songAudiofilesUri,
    method: 'GET',
    header: {
        'x-access-token': pm.environment.get("session_token"),
        'content-type': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ songId: pm.environment.get("song_id")})
    }
}

When I send this to my endpoint, the body of the request appears to be empty on the server side.
When I send the same request with the regular postman GUI I have no trouble and the endpoint works.

I logged the body to the console just to be sure, it's not an issue with the environment variable, but everything looks normal there:
Bildschirmfoto 2019-08-16 um 15 45 34

Has anyone seen something like this before?
Is this an Issue with Postman?

@sdnts
Copy link
Author

sdnts commented Aug 22, 2019

Perhaps @prashantagarwal would be able to help you out @enedrio

@lmunarim
Copy link

lmunarim commented Nov 1, 2019

pm.sendRequest({
url: pm.environment.get("Ambiente")+"/Seguranca/GerarToken",
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {
mode: 'urlencoded',
urlencoded: [
{key: "username", value: pm.globals.get("usuario"), disabled: false},
{key: "password", value: pm.globals.get("senha"), disabled: false}
]
}
}, function (err, res) {
pm.globals.set("TOKEN", res.json().result);
});

image

image

ficou top!!!! ajudou muito :)

@qadatta
Copy link

qadatta commented Dec 4, 2019

I wonder if what @tepease asked is possible. Suppose I already have various requests defined in Postman itself, is it possible to simply invoke one, instead of writing it from scratch?

I am also looking for a way to execute existing postman script in collection so that I don't need to write everything whats there already in existing request saved in collection. I just want to call that script in pre-script.

@sdnts
Copy link
Author

sdnts commented Dec 4, 2019

@qadatta Maybe you could take a look at postman.setNextRequest here. You might need to tinker with the order of requests obviously, but I believe it should be possible.

@qadatta
Copy link

qadatta commented Dec 4, 2019

Thanks @madebysid! I will take look and implement.

@gregrobson
Copy link

For anyone else doing this integration, here's my example with v2 of Zoho's API.

I'm assuming that your client has already sent the temp-code if you have used the self client feature and you have got a refresh token in your collection variables.

You should just need to set Authorization to {{zoho_access_token}} in your headers for the requests.

// Refresh the access token and set it into environment variable
pm.sendRequest({
    url:  pm.collectionVariables.get("zoho_accounts_endpoint") + "/oauth/v2/token", 
    method: 'POST',
    header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
            {key: "client_id", value: pm.collectionVariables.get("zoho_client_id"), disabled: false},
            {key: "client_secret", value: pm.collectionVariables.get("zoho_client_secret"), disabled: false},
            {key: "refresh_token", value: pm.collectionVariables.get("zoho_refresh_token"), disabled: false},
            {key: "grant_type", value: 'refresh_token', disabled: false}
        ]
    }
}, function (err, res) {
    pm.collectionVariables.set("zoho_access_token", 'Zoho-oauthtoken ' + res.json().access_token);
});

@LuisLuyo
Copy link

Hello there!, what would happen if I want to get a header data (of pm.sendRequest)? What would the Code look like?

For Example:

const echoPostRequest = {
    url: 'http://IP:PORT/grantingTicket/VXX',
    method: 'POST',
    header: 'Content-Type:application/json',
    body: {
        mode: 'raw',
        raw: JSON.stringify({
            "authentication": {
            "consumerID": "xxxxxxxx",
            "authenticationType": "xx",
            "userID": "xxxxxx"
            },
            ....
        })
    }
};
pm.sendRequest(echoPostRequest, function (err, res) {
    console.log(err ? err : res.json());
    //var tsec = postman.getResponseHeader("tsec");                ?????
    pm.globals.set("tsec_gt", res.getResponseHeader("tsec"));    ?????
    // tsec is in header. I want to get this variable "tsec".
});

Please Help me!

Thanks

@fabriziospurio
Copy link

thank you for the useful information

@hazmeister
Copy link

@LuisLuyo

I had similar trouble fetching headers. Here's what I did:

pm.sendRequest({
    url: pm.environment.get("ENDPOINT") + '/login?username=user&password=passw0rd',
    method: 'POST'
}, function (err, res) {
    var headers = res.headers.toObject();
    pm.environment.set("BEARER_TOKEN", headers.authorization);
});

@mikolec
Copy link

mikolec commented Apr 14, 2020

I had similar problem. I have noticed that 0Auth2 using client_credentials worked for a single request, but I couldn't make it work on Collection level. What I have noticed is that on request level it was using 'Content-Type': 'application/x-www-form-urlencoded'.
I have made it work like this:

pm.sendRequest({
      url:  pm.environment.get("tokenUrl"), 
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': pm.variables.get("authorization") 
      },
      body: {
          mode: 'urlencoded',
          urlencoded: [
            {key: "grant_type", value: "client_credentials", disabled: false},
            {key: "username", value: pm.environment.get("clientId"), disabled: false},
            {key: "password", value: pm.environment.get("clientSecret"), disabled: false},
            {key: "scope", value: pm.environment.get("scope"), disabled: false }
        ]
      }
  }, function (err, response) {
		let jsonResponse = response.json(),
        newAccessToken = jsonResponse.access_token;
       
		pm.environment.set('accessToken', newAccessToken);
		pm.variables.set('accessToken', newAccessToken);
  });

The authorization is sth like: Basic c2VydmljZSlongstringTJBMjBSano4WQ== . I've got from console after generating single auth request first with clientSecret.
I'm then using {{accessToken}} template for the Collection's Access Token and "Inherit auth from parent" on request level

@lejohurtado
Copy link

@mikolec

the authorization is: "Basic "+ btoa("Client IF":"Client secret")

@hairinwind
Copy link

I am running a post request. Before that, I want to run a DELETE request to avoid duplication.
I knew I can do a pm.sendRequest in pre-request. But my request has a lot of head values. It is annoying to copy them.
Can we have something like postman.setPreviousRequest("the_request_name") which is similar to postman.setNextRequest().

@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