Postman Pre-Request Script to access secured API with bearer token

Natsu
3 min readMar 19, 2021

When we secure any API with OAuth, we need to call the API with the access token Authorization header.

The issue comes when an access token gets expired and we have to request a new access token and change our header token, again and again, to make an API call through the Postman.

In postman, we can define a pre-request script to avoid this, and the API will always get the token before calling the secured API. We don’t have to manually define the access token using the header when we call the API.

You can use the below postman pre-request script to avoid the manual OAuth token call.

postman pre-request script to get access token

Below are the postman information for the above pre-request script.

Access Token Request Header
Access Token Request Body
Access Token Response

Access the secured API request using bearer token and response

secured API request & response

We can check the token request API and secured API call through postman console. We have to do two separate API call to access any secured API.

Postman console view of separate access token request and API call

After we implement the pre-request script; the postman API can call the token API internally inside every secured API call.

We can now call the secured API directly without worrying about the expiration time of access token. Once we call the API, we can check through the console to see the API request.

Postman console view of secure API call with token request

Let’s understand the code block. The script first call the token request and getting the response. After the JSON response received, script will assign the access token value to the header. It is simple as that.

Inside the pm.sendRequest() function we define our URL, method, header, and body values.

Below line will assign the access token to the header value.

pm.request.headers.append(Header.create('Bearer ' + res.json().access_token, 'Authorization'));

Extra information about postman scripts. We can define variables and assign the values to those variables and use them anywhere in the script.

To set a variable in the postman environment, use the below line.

pm.environment.set("token_variable", res.json().access_token);

To access the above environment variable, use the below code.

pm.environment.get("token_variable")

This pre-request script will call the token request API, every time we call the secured API through postman. If we need to check the API response time or performance tunings, better to avoid this method and use a manual way to check the API performance.

--

--