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

JavascriptPostman

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

A little late but for others who come across this post, it IS now possible to send another request from the Pre-request Script section. A few examples can be found here : https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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! :)

Solution 7 - Javascript

You can use a function sendRequest of postman.

Some examples here.

https://gist.github.com/madebysid/b57985b0649d3407a7aa9de1bd327990

Solution 8 - Javascript

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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLasharelaView Question on Stackoverflow
Solution 1 - JavascriptGera ZenobiView Answer on Stackoverflow
Solution 2 - JavascriptHanneleView Answer on Stackoverflow
Solution 3 - JavascriptKBuscView Answer on Stackoverflow
Solution 4 - JavascriptPiotr DawidiukView Answer on Stackoverflow
Solution 5 - JavascriptMichael OrmrodView Answer on Stackoverflow
Solution 6 - JavascriptAli Rıza ŞahinView Answer on Stackoverflow
Solution 7 - JavascriptFlavio RamosView Answer on Stackoverflow
Solution 8 - Javascriptsurya pratap singhView Answer on Stackoverflow