Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
});
@jmoont

This comment has been minimized.

Copy link

@jmoont jmoont commented Sep 7, 2017

I thought this example might also be helpful. It is being used in a Pre-request script in order to get the authentication header needed for the request. Email and password are saved in environment variables.

The authorization environment variable is updated by the script and can then be used in the header with the {{authorization}} syntax.

pm.sendRequest({
    url: pm.environment.get("api-url") + 'v1/authenticate',
    method: 'POST',
    header: {
        'content-type': 'application/json',
        'x-site-code': pm.environment.get("x-site-code")
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ email: pm.environment.get("email"), password: pm.environment.get("password") })
    }
}, function (err, res) {
    pm.environment.set("authorization", "Bearer " + res.json().token);
});
@dmartinlozano

This comment has been minimized.

Copy link

@dmartinlozano dmartinlozano commented Sep 8, 2017

More examples (Thanks @jmoont for your help :) )

pm.sendRequest({
      url:  pm.environment.get("OAUTH_URL")+"/uaa/oauth/token", 
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic Abcdefghijk=='
      },
      body: {
          mode: 'urlencoded',
          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}
        ]
      }
  }, function (err, res) {
        pm.globals.set("token", res.json().access_token);
  });
@jose-neta

This comment has been minimized.

Copy link

@jose-neta jose-neta commented Oct 26, 2017

guys sorry to pollute this excellent reference with a doubt, but here it goes, I hope you'll find the use case interesting also:

on a pre-run script

pm.environment.set("token", pm.environment.get("admin_token"));

pm.sendRequest({
    url: "http://127.0.0.1:5000/api/toggles/{{$guid}}", // PM dynamic var
    method: "PUT",
    header: {
        "Content-Length": "1",
        "Authorization": "Bearer {{token}}",
        "Content-Type": "application/json"
    },
    body: {},
    function (err, res) {
        pm.environment.set("toggle_id", res.json().name)
    }
});

Problem

running the request above will correctly create the toggle but will not set up the pm.environment variable "toggle_id".

I've attached an image that illustrate the responses.

Note that the Tests script is trying to get the supposedly set "toggle_id" into tid var but there is no toggle_id and it should :(
As far as I could learn from you examples above I supposedly doing the things right.
screenshot

/cc @dmartinlozano @madebysid @jmoont

@abhijitkane

This comment has been minimized.

Copy link

@abhijitkane abhijitkane commented Oct 26, 2017

@jose-neta The function needs to be the 2nd argument of the pm.sendRequest function, not a property of the first argument.

This works:

pm.sendRequest({
    url: "",
    method: "PUT",
    headers: {},
    body: {}
 },
 function (err, res) {
    pm.environment.set("toggle_id", res.json().url);
 }
);
@jose-neta

This comment has been minimized.

Copy link

@jose-neta jose-neta commented Oct 26, 2017

ouch! that one was easy O:) Javascript is always on my way. Thank you @abhijitkane.
Nevertheless I hope to have contributed to examples above 👍

@merjduran

This comment has been minimized.

Copy link

@merjduran merjduran commented Feb 3, 2018

@jmoont @dmartinlozano was hoping you could help me with this. Im getting this error when using the code you have provided above:
{
"statusCode": 401,
"status": "Unauthorized",
"errorMessage": "Authorization Failed."
}

@tepease

This comment has been minimized.

Copy link

@tepease tepease commented Apr 4, 2018

Is there any way to run a saved request in this script instead of writing it from scratch?

@tegomass

This comment has been minimized.

Copy link

@tegomass tegomass commented Apr 6, 2018

Possible to set a timeout to the request ?

@jayarjo

This comment has been minimized.

Copy link

@jayarjo jayarjo commented Jul 12, 2018

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?

@AlexanderTunick

This comment has been minimized.

Copy link

@AlexanderTunick AlexanderTunick commented Jul 17, 2018

Hello guys. Sorry if it's a topic for this, but nobody described hot to make multiple requests with explicit structure?
Did anybody do it?

@jaredhanks

This comment has been minimized.

Copy link

@jaredhanks jaredhanks commented Jul 20, 2018

How would you do this if the response is XML? Normally I just use something like:
var jsonObject = xml2Json(responseBody);
postman.setEnvironmentVariable("TOKEN", jsonObject.token);
but that doesn't seem to work in this scenario.

@japena03

This comment has been minimized.

Copy link

@japena03 japena03 commented Jul 26, 2018

If i have an existing request (login) in Postman already is there a way to simply reference that request in Pre-request script?

@user001K

This comment has been minimized.

Copy link

@user001K user001K commented Jul 27, 2018

Hi all, I am new to Postman test and pre-req scripts. However, I was able to trigger a post req (A) from the pre-req scripts of another GET req (B).
Now, the response body of POST req A has a token that I am setting to an env variable using the Test scripts of POST req A, as I need it for my GET req B, as an Authorization token.

I believe, when executing the req A from pre-req scripts of req B, the Test scripts of req A don't seem to execute. Any idea, what am I doing wrong here.

Thanks in advance.

@ggutenberg

This comment has been minimized.

Copy link

@ggutenberg ggutenberg commented Aug 28, 2018

I think this syntax is wrong and introduces an async problem:

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');
    });
});

I found that when I would do this, a failing assertion would log in the console but the test would still pass. The correct syntax (or at least the syntax that worked for me) should be:

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

In other testing libraries I'd do something like:

pm.test("Status code is 200", function (done) {
    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');
        done();
    });
});

But that doesn't work here and throws an error.

@user001K this might solve your problem as well.

@musamamasood

This comment has been minimized.

Copy link

@musamamasood musamamasood commented Oct 9, 2018

More examples (Thanks @jmoont for your help :) )

pm.sendRequest({
      url:  pm.environment.get("OAUTH_URL")+"/uaa/oauth/token", 
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': 'Basic Abcdefghijk=='
      },
      body: {
          mode: 'urlencoded',
          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}
        ]
      }
  }, function (err, res) {
        pm.globals.set("token", res.json().access_token);
  });

Working perfectly.

@BorysovAndriu

This comment has been minimized.

Copy link

@BorysovAndriu BorysovAndriu commented Oct 29, 2018

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);
});

@Sussumu

This comment has been minimized.

Copy link

@Sussumu 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

This comment has been minimized.

Copy link

@JenteVH 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

This comment has been minimized.

Copy link

@d4rkd0s 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

This comment has been minimized.

Copy link

@zeckdude 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

This comment has been minimized.

Copy link

@enedrio 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?

@madebysid

This comment has been minimized.

Copy link
Owner Author

@madebysid madebysid commented Aug 22, 2019

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

@lmunarim

This comment has been minimized.

Copy link

@lmunarim 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

This comment has been minimized.

Copy link

@qadatta 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.

@madebysid

This comment has been minimized.

Copy link
Owner Author

@madebysid madebysid 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

This comment has been minimized.

Copy link

@qadatta qadatta commented Dec 4, 2019

Thanks @madebysid! I will take look and implement.

@gregrobson

This comment has been minimized.

Copy link

@gregrobson gregrobson commented Jan 28, 2020

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

This comment has been minimized.

Copy link

@LuisLuyo LuisLuyo commented Feb 13, 2020

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

This comment has been minimized.

Copy link

@fabriziospurio fabriziospurio commented Mar 20, 2020

thank you for the useful information

@hazmeister

This comment has been minimized.

Copy link

@hazmeister hazmeister commented Mar 25, 2020

@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

This comment has been minimized.

Copy link

@mikolec 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

This comment has been minimized.

Copy link

@lejohurtado lejohurtado commented May 8, 2020

@mikolec

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

@hairinwind

This comment has been minimized.

Copy link

@hairinwind hairinwind commented May 9, 2020

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

This comment has been minimized.

Copy link

@lflucasferreira lflucasferreira commented Jun 12, 2020

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

This comment has been minimized.

Copy link

@RadwaSaleh RadwaSaleh commented Sep 3, 2020

disabled: false

are keys by default disabled?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.