Authorization type Bearer Token on Postman

cyb3rZ picture cyb3rZ · Aug 23, 2018 · Viewed 11.4k times · Source

I'm trying test a few endpoints using Postman.

All endpoint, require a token which can be obtain by log-in.

So I did this :

Request #1

enter image description here

After login success, I have access to the token from the response, then I store that token in my global variable.

let token = pm.response.json().location
console.log('Token : ', token.split("?token=")[1]);
pm.globals.set("token", token)

I need to use that token as Authorization type Bearer Token for my request #2.

enter pastedescription here

I can copy & paste that in the token box, but I tried to avoid doing that manually, is there a way to do it automatically so I can run these 2 requests in sequence?

Answer

Wilfred Clement picture Wilfred Clement · Aug 24, 2018

At first, create an environment ( top right corner of postman - image below ) This is not a mandatory step by I suggest you to do for better handling of variables

enter image description here

I have modified the script to suit your need

var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("ID", jsonData.Location.split("?token=")[1]);

Now this will export the value of the token ( screenshot below )

enter image description here

All you have to do next is to call the variable in request #2

enter image description here

By this you don't have to manually copy, paste into request #2 every single time