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

Lasharela picture Lasharela · Sep 17, 2016 · Viewed 58.2k times · Source

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?

Answer

Gera Zenobi picture Gera Zenobi · Dec 18, 2018

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.