Saturday, March 6, 2021

Postman Pre-Request: How to get Auth Token at Collection level?

Prerequisite:

You need latest Postman application installed.

You can download Postman application from here.

Steps:

  • Create a new collection.
  • Open the collection and click on Pre-request Script.
  • Paste below code there:
pm.sendRequest({
url: [AUTH_TOKEN_URL],
method: 'POST',
header: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "client_id", value: [CLIENT_ID_VALUE] },
{ key: "client_secret", value: [CLIENT_SECRET_VALUE] },
{ key: "resource", value: [RESOURCE_VALUE] },
{ key: "grant_type", value: [GRANT_TYPE_VALUE] }
]
}
}, function (err, response) {
if (null != err) {
const jsonResponse = response.json();
// Save token to env variable.
pm.environment.set('env_auth_token', jsonResponse.token);
} else {
console.log("Cannot fetch Auth token");
pm.environment.set('env_auth_token', '');
}
});

  • Replace all values as per your requirements.