DEV Community

Cover image for Setting Up Postman and Automatically Adding Bearer Tokens
Amran Hussein
Amran Hussein

Posted on

Setting Up Postman and Automatically Adding Bearer Tokens

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

Some developers face this small issue which when testing REST APIs they need to fetch and attach bearer tokens to make testing REST APIs every each time when tokens expire. So, here's the solution to avoid repeating the same process of fetch and attaching bearer tokens all the time.

All you need to write a few lines of code in the pre-request script in the request collection. In this guide, you will learn how to use a pre-request script to fetch and attach bearer tokens to make testing your REST APIs easier, check below the example.

This is the authentication API that generates bearer tokens. API [A]

Image description

This is the API request that needs to attach the bearer token in it. API [B]

Image description

These are a few lines of code you need to write in a pre-request script in the API [B] and you can make a call request without fetching bearer token from API [A] and attach it in API [B].

BASE_URL_NAVITAIRE = the URL and sets as an environment variable
NAVITAIRE_TOKEN = bearer token and sets as an environment variable

const baseUrl = pm.environment.get("BASE_URL_NAVITAIRE")

pm.sendRequest({
    url: baseUrl + '/nsk/v1/token',
    method: 'POST',
    header: {
        'content-type': 'application/json'
    },
    body: {
        mode: 'raw',
        raw: JSON.stringify({ 
        "credentials": {
        "username": "TOPWCHCKINSTG",
        "password": "6F6wSzBa*qBD"
    }})
    }
}, (err, res) => pm.environment.set("NAVITAIRE_TOKEN", res.json().data.token));
Enter fullscreen mode Exit fullscreen mode

Image description

Top comments (1)

Collapse
 
ishakmohmed profile image
Mohmed Ishak

It has less explanation yet is full of explanation.