Generating access_token every one hour while development on Postman is tiring. Postman has a nifty feature called pre-request scripts, which can be run before every request on a Collection. This post shows how it can be used to automate access_token generation.

Prerequisite

This post assumes that you have the following in possession

  • client_id
  • client_secret
  • refresh_token
  • Zoho Data Center - API endpoint TLD various based on this. If you’re on US DC, authentication endpoint will be https://accounts.zoho.com while if you’re on IN DC, endpoint will be https://accounts.zoho.in. The same is applicable for other DCs.

Setting up variables

Postman offers setting up variables with different scopes via mechanisms like Collection variables, Global variables and Environment variables. Variables defined at a Collection are available to all the requests inside that Collection. Global variables are available to all requests, while Environment variables are available only when they are selected.

In our case we have the following variables to be setup with the mentioned scopes, you can change this as you find suitable. However, make sure to make the necessary changes at scripts later on also.

ScopeVariableDescription
Globaltoken_expiryKeep track of token expiry
Globalauth_endpointAuthentication Endpoint
Global{product}_endpointAPI endpoint for product in use like Zoho CRM, Zoho Desk etc,.
Environmentclient_idClient ID obtained from Zoho API Console
Environmentclient_secretClient Secret from Zoho API Console
Environmentrefresh_tokenRefreshe token which doesn’t change for defined scope
Environmentaccess_tokenAccess Token which has validity of one hour

Configuring Authentication

Make sure to add Authentication to either API Key or Bearer Token for Collection to access_token. So any request on this collection inherit it.

Pre-request script for Collections

Once the information above available, we can proceed to set up the pre-request script at the collection level.

// API request to generate new access token
const requestGenerateToken = {
    url:  pm.globals.get("auth_endpoint") + "/oauth/v2/token",
    method: 'POST',
    header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: {
        mode: 'urlencoded',
        urlencoded: [
            {key: "client_id", value: pm.environment.get("client_id")},
            {key: "client_secret", value: pm.environment.get("client_secret")},
            {key: "refresh_token", value: pm.environment.get("refresh_token")},
            {key: "grant_type", value: 'refresh_token'}
        ]
    }
}

var getToken = true;

// Check if token needs to be refresh
if(!pm.globals.get("token_expiry") || !pm.environment.get("access_token")) {
    console.log("Token or expiry date missing")
} else if (pm.globals.get("token_expiry") <= (new Date().getTime())) {
    console.log("Token is expired")
} else {
    getToken = false;
}

// If token needs to refresh, generate new token
if (getToken === true) {
    pm.sendRequest(requestGenerateToken, function (err, res) {
    console.log(err ? err : res.json());
        if (err === null) {
            var responseJson = res.json();
            pm.environment.set('access_token', responseJson.access_token)
            var expiryDate = new Date();
            expiryDate.setSeconds(expiryDate.getSeconds() + responseJson.expires_in);
            pm.globals.set('token_expiry', expiryDate.getTime());
        }
    });
}

Once this is configured, anytime a request is sent from the Collection, it will check for access_token and get new one if doesn’t already exist.