How to automatically set a Bearer Token for your Postman requests?

I am trying to add bearer tocken to all the request calls within the collection.Please help!

Hi @d.rajkhowa02, welcome to our community! :vulcan_salute:

I use this in my context, I put this piece of code on my collection Pre-Request Scritps.

pm.sendRequest({
    url: YourURL
    method: 'POST',
    header: {
        'content-type': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ YOUR PARAM TO CREATE THE TOKEN IF NEED IT })
    }
}, (err, res) => pm.collectionVariables.set("TOKEN", res.json().accessToken));

Then on collection Authorization I insert the variable TOKEN and change the Type to Bearer Token. That will help on your problem.

:vulcan_salute:

Hi @d.rajkhowa02

You can do in other way also .Set a environment variable with the name Token . Below are the script you can write down inside Test tab.

var res = JSON.parse(responseBody);
if(data.KeyName === ‘Your API KEY Name’)
{
pm.environment.set(“Your variable name”, res.token);
}

it will save the token value inside the variable what you declared in environment .

For this you have to make a csv file with two field Key name and Keyvalue .that can be passed with the help of post man runner,select your environment there .

Defiantly it ll work .I have done in the same way.