Lasharela
Lasharela

Reputation: 1547

How to run one request from another using Pre-request Script in Postman

I'm trying to send an authenticated request with one click in postman.

So, I have request named "Oauth" and I'm using Tests to store the token in a local variable.

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.access_token);

What I'm trying to do now is that run the Oauth request automatically (from a pre-request script) for any other requests which needs a bearer token.

Is there a way to get an access token and send an authenticated request with one postman button click?

Upvotes: 96

Views: 168338

Answers (12)

Flavio Ramos
Flavio Ramos

Reputation: 1

You can use a function sendRequest of postman.

Some examples here.

https://gist.github.com/b57985b0649d3407a7aa9de1bd327990

Upvotes: -1

Victor Santaterra
Victor Santaterra

Reputation: 21

This works to me:

Authorization method Test:

pm.environment.set("auth-request", {
  parameters: {
    url: pm.request.url,
    method: pm.request.method,
    header: pm.request.headers,
    body: pm.request.body
  },
  callback: `(_, authResponse) => pm.environment.set("token", authResponse.json().token)`
})

Authorized endpoints Pre-request Script

const { parameters, callback } = pm.environment.get("auth-request")
pm.sendRequest(parameters, eval(callback))

Upvotes: 2

Ukpa Uchechi
Ukpa Uchechi

Reputation: 730

Don't know if this helps, but what I did when I wanted one function to run before another was this. I added the below code to the pre-request script

 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);
    // then called the other request here
    SecondRequest();
});

//Then I created a function 

function SecondRequest(){
    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);
});
}

This is what I did, any reservations are always welcome.

Upvotes: 1

MSS
MSS

Reputation: 3860

If you are setting token in your auth token you can copy its request configuration to env once (in test script section) and automatically call it from other request and use token from env.

It originally mentuioned here: https://community.postman.com/t/use-existing-postman-request-in-pre-post-script/23477/5

  1. Copy current request config to env in auth test script:

    let r=pm.response.json();

    pm.environment.set("access_token", r.access_token); pm.environment.set("refresh_token", r.refresh_token);

    pm.environment.set("auth_req", pm.request);

save postman current request config to env

And then call it on other endpoints:

pm.sendRequest(pm.environment.get("auth_req"))

run postman request from env config

Upvotes: 3

First, add pre-request script:

enter image description here

pm.sendRequest({
    url: 'http://YOUR_SITE',
    method: 'POST',
    body: {
        mode: 'urlencoded',
        urlencoded: [
            { key: "login", value: "YOUR_LOGIN" },
            { key: "password", value: "YOUR_PASSWORD" }
        ]
    }
}, function (err, res) {
    if (err === null) {
        pm.globals.set("token", res.json()["access_token"]);
    }
});

Second, set custom variable(after you can use it value):

enter image description here

Third, you can use variable by {{VARIABLENAME}}, for example:

enter image description here

Upvotes: 10

Michael Ormrod
Michael Ormrod

Reputation: 151

You can add a pre-request script to the collection which will execute prior to each Postman request. For example, I use the following to return an access token from Apigee

const echoPostRequest = {
  url: client_credentials_url,
  method: 'POST',
  header: 'Authorization: Basic *Basic Authentication string*'
};

var getToken = true;

if (!pm.environment.get('token')) {
  console.log('Token  missing')
} else {
  console.log('Token all good');
}

if (getToken === true) {
  pm.sendRequest(echoPostRequest, function(err, res) {
    console.log(err ? err : res.json());
    if (err === null) {
      console.log('Saving the token');
      console.log(res);
      var responseJson = res.json();
      console.log(responseJson.access_token);
      pm.environment.set('token', responseJson.access_token)
    }
  });
}

Upvotes: 4

juslintek
juslintek

Reputation: 511

All these workarounds with recreating requests. Postman does not support what you want to do. In order to get what you want, you have to use Insomnia, it allows you to map body values from other request responses and if those responses are not executed ever it automatically runs them or behaves based on chosen policy.

But if you want to stick with Postman, then you'll have to save full previous request params to global variables, then retrieve all configuration of previous requests from that variable as a JSON string, parse that JSON into an object and assign it to pm.sendRequest as the first argument.

Upvotes: 7

Riza Sahin
Riza Sahin

Reputation: 71

The same question was on my mind, which is basically "how can I run another request that already exists from another request's test or pre-request script tabs without building that request with pm.sendRequest(reqConfObj)?", then I found the postman.setNextRequest('requestName') method from this Postman discussion which is gonna lead you to this postman documentation page about building request workflows.

But the thing is, postman.setNextRequest() method will not run if you are not running a folder or a collection, so simply hitting the 'Send' button of the request that has your script won't work.

I also would like to draw your attention towards some things:

  • The prepended word, it's 'postman' instead of 'pm'.
  • postman.setNextRequest() will always run last, even though you have written it to the top of your script. Your other code in the script will be ran and then postman.setNextRequest will initialize.
  • If you would like to stop the request flow, you could simply postman.setNextRequest(null).

I would encourage everyone that uses Postman to check out the links that was mentioned, I believe it's a great feature that everybody should give it a try! :)

Upvotes: 7

surya pratap singh
surya pratap singh

Reputation: 1

I have tried multiple solutions, the below solution is related to when you are parsing the response for request 1 and passing any variable into the second request parameter. ( In this Example variable is Lastname. )

Note:- data and user are JSON objects.``

postman.clearGlobalVariable("variable_key");
postman.clearEnvironmentVariable("variable_key");
tests["Body matches string"] = responseBody.has("enter the match string ");
 var jsonData = JSON.parse(responseBody);
  var result = jsonData.data;
  var lastName = result.user.lastName;
tests["Body matches lastName "] = responseBody.has(lastName);
tests["print  matches lastName " + lastName ] = lastName;

Upvotes: -1

Hannele
Hannele

Reputation: 9666

NOTE: There now is a way to do this in a pre-request script, see the other answers. I'll keep this answer for posterity but just so everyone knows :)

I don't think there's a way to do this in the pre-request script just yet, but you can get it down to just a few clicks if you use a variable and the Tests tab. There are fuller instructions on the Postman blog, but the gist of it is:

  1. Set up your authentication request like normal.
  2. In the Tests section of that request, store the result of that request in a variable, possibly something like the following:

    var data = JSON.parse(responseBody);
    postman.setEnvironmentVariable("token", data.token);
    
  3. Run the authentication request -- you should now see that token is set for that environment (click on the eye-shaped icon in the top right).

  4. Set up your data request to use {{token}} wherever you had previously been pasting in the bearer token.
  5. Run your data request -- it should now be properly authenticated.

To refresh the token, all you should need to do is re-run the authentication request.

Upvotes: 27

Gera Zenobi
Gera Zenobi

Reputation: 1440

As mentioned by KBusc and inspired from those examples you can achieve your goal by setting a pre-request script like the following:

pm.sendRequest({
    url: pm.environment.get("token_url"),
    method: 'GET',
    header: {
        'Authorization': 'Basic xxxxxxxxxx==',
    }
}, function (err, res) {
    pm.environment.set("access_token", res.json().token);
});

Then you just reference {{access_token}} as any other environment variable.

Upvotes: 73

Piotr Dawidiuk
Piotr Dawidiuk

Reputation: 3092

You can't send another request from Pre-request Script section, but in fact, it's possible to chain request and run one after another.

You collect your request into collection and run it with Collection Runner.

To view request results you can follow other answer.

Upvotes: 11

Related Questions