Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 783
Lasharela Avatar asked Sep 17 '16 20:09

Lasharela


People also ask

What is the use of pre request script in Postman?

The pre-request script is the entry point for request execution in Postman. If there is any script/logic added as a part of the pre-request script that gets executed first following which the actual request execution takes place and once the response is received, the tests or the post request scripts get executed.


2 Answers

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.

like image 193
Gera Zenobi Avatar answered Sep 23 '22 10:09

Gera Zenobi


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

like image 23
KBusc Avatar answered Sep 20 '22 10:09

KBusc