Automating DADI API authentication in Postman

Probably the greatest productivity hack of all time

If your applications consume content from APIs or headless content management systems, you probably have your favourite tool for interacting with them for development and debugging purposes. At DADI, we’re big fans of Postman, as it offers a friendly interface for querying an API using the various HTTP verbs, with convenient controls for the request headers, body and other niceties.

One of those niceties is the ability to specify a pre-request script — a block of JavaScript code defined by the user, to be executed immediately before the HTTP request is triggered. We’ll use this to achieve what has got to be the greatest DADI API productivity hack of all time (it certainly was to me). First, let’s talk about authentication.

Authentication in DADI API

DADI API uses 2-legged oAuth to authenticate requests. Each client is given a set of credentials in the form of an ID+secret pair, which in itself can’t be used to authenticate requests. An additional step is required, whereby clients exchange their credentials for a bearer token, a self-expiring code that is added to the Authorization HTTP header to authenticate requests.

This exchange happens in another HTTP request:

  1. The client sends a POST request with their credentials to the /token endpoint;
  2. The API replies with a new bearer token (and the amount of time it will live for).

This flow is ideal for machine-to-machine communication (and Passport can help make that seamless), but when a human is developing or debugging an API, doing this process manually and repeatedly can get a-nnoy-ing really quickly. Luckily, we can use Postman’s pre-request scripts to automate it.

Pre-request scripts to the rescue

So, here’s the idea. We’ll use a pre-request script to automate the 2-legged oAuth flow, so that on each request we’ll ping the /token endpoint with our credentials, read the bearer token from the response and attach it to the main request, so that we’re always authenticating with a fresh bearer token.

The first step is to create an Environment in Postman, which is a saved session with support for user-defined variables. We’ll use it to store the credentials, so I typically use one for each API project I’m working on.

Click the gear icon on the top-right corner and select Manage Environments, which will open a modal. In there, click Add and create two variables: clientId and secret, with your client’s ID and secret as their respective values.

Back to the request window, navigate to the Pre-request script tab and add the following:

const url = request.url
const pathPos = url.split('').findIndex((char, index) => {
return (char === '/') && (url[index - 1] !== '/') && (url[index - 1] !== ':')
}) || Infinity
const baseUrl = url.slice(0, pathPos)
url: baseUrl + '/token',
method: 'POST',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json'
body: {
mode: 'raw',
raw: JSON.stringify({
clientId: pm.environment.get('clientId'),
secret: pm.environment.get('secret')
}, (err, res) => {
pm.globals.set('bearer', res.json().accessToken);

So, what’s happening here? We’re making a request to the /token endpoint with the credentials that we’ve stored in the environment variables. When the result comes back, we extract the bearer token from the accessToken property and store it in a global variable called bearer.

The final step is to inject the contents of this new variable into the headers of our request. Navigate to the Headers tab and add an entry with the key Authorization and a value of Bearer {{bearer}} – the curly braces signal a variable, telling Postman to replace it with the contents of the variable we created in the pre-request script.

That’s it!

Easy, right? Once you click Send, the request will be automatically authenticated. You can use the extra time on your hands to build more cool stuff with the DADI stack.

Do you have any other productivity hacks you can’t live without? I’d love to hear abou them! Find me on Twitter or come chat with our team on Discord or Telegram.

Written by Eduardo Bouças, principal Engineer at DADI. Eduardo leads the development of several DADI web services, including DADI CDN.

Like what you read? Give DADI a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.