Skip to main content

Automating Token Retrieval in Web Queries

Some APIs require you to obtain a short-lived access token before making data requests. This article explains how to configure Informer to automatically retrieve a token using a POST request, then use that token in a follow-up request—all within a Web Datasource. This approach eliminates the need to manually copy tokens from Postman or other tools.

Handling Token Exchange in API Requests

Many APIs use OAuth2 authentication, where you must first POST to a token endpoint with credentials and parameters (such as grant_type=client_credentials) to receive an access_token. This token is then used as a Bearer token in the Authorization header for subsequent requests. Since these tokens often expire quickly, automating this process in Informer is essential. The steps for this logic are as follows:

1. Enable POST Requests in Your Web Datasource​

  • In Informer, create or edit your Web Datasource.
  • Check the option to "Allow POST Requests."

2. Configure the Token Request​

  • Create a new query in your Web Datasource.
  • Set the HTTP method to POST.
  • Set the URL of the request to be whichever endpoint grants the temporary authorization token.
  • Add any required Header or POST Data information, such as client_id or client_secret, as needed by your API.

3. Set Up the Custom Response Parser​

  • In the Response Parser section, use the next() function to chain the token request and the data request.

Example script:

if (isFirstResponse()) {
const url = 'next/endpoint/to/hit'; // Adjust as needed
const nextConfig = _.assign({}, response.config);
nextConfig.url = url;
nextConfig.method = 'get';
nextConfig.headers.Authorization = 'Bearer ' + response.data.access_token;
next(nextConfig);
} else {
push(response.data);
}
  • Make sure the URL for the second request matches your API's requirements.

4. Test and Adjust​

  • Run the query and check the results.
  • If you receive a 404 or 401 error, double-check the endpoint URL and the Authorization header format.
  • Adjust the script as needed for your API's specific requirements.

Tips​

  • Always confirm the exact endpoint and required headers with your API documentation.
  • If your API requires additional parameters in the POST body, add them in the POST Data tab.
  • The access_token is typically found in the response as response.data.access_token, but this may vary.