Refreshing Access Token

An example of how the authentication access token can be refreshed automatically.

Overview

When running integrations continuously, authentication towards the API must be refreshed periodically. By default, this must be done every hour and should happen automatically without interfering with the integration. In this example, a simple access token refresh routine that keeps the API authenticated has been implemented.

Preliminaries

  • Service Account Credentials You must create and know the credentials of a Service Account. Any role will suffice.

  • OAuth2 This example heavily builds on the OAuth2 Authentication Guide. It is recommended that you understand this routine before attempting to expand upon it.

Example Code

The following points summarize the provided example code.

  • A simulated REST API call is triggered every 5 seconds.

  • An instance of the Auth class provides the access token as required.

  • If the access token is within 1 minute of expiration, the token is first refreshed.

Environment Setup

If you wish to run the code locally, make sure you have a working runtime environment.

The following packages are required by the example code and must be installed.

pip install pyjwt==2.7.0
pip install requests==2.31.0

Add the following credentials to your environment as they will be used to authenticate the API.

Source

The following code snippet implements the token refresh routine.

Expected Output

For visualization purposes, an expiration timer is printed each time the token is used.

Last updated

Was this helpful?