Obtain Access Token (Python)

This guide offers a Python code example for obtaining and managing access tokens for the 24SevenOffice API, ensuring automatic token renewal and seamless API integration.

Here, you’ll find a straightforward guide on how to securely obtain and use an access token for the 24SevenOffice API. Whether you’re a seasoned developer or just starting out, this page is designed to help you integrate our API smoothly and keep your access tokens valid at all times.

 

Disclaimer 

The code examples and implementation details provided on this page are for demonstration purposes only. They are intended to guide you in integrating with the 24SevenOffice API and managing access tokens. However, they may not account for all security considerations specific to your environment or application. It is your responsibility to review, test, and ensure that any implementation meets your security and operational requirements. 24SevenOffice assumes no liability for any potential security breaches, data loss, or other risks arising from the use of these examples. Please consult with your development and security teams to ensure that your integration is secure and compliant with best practices.

What’s an Access Token?

An access token is your gateway to accessing the 24SevenOffice API. It allows you to authenticate your requests and interact with our ERP features securely. However, tokens can expire, so you need to ensure your application always uses a valid token.

Access Token Documentation

Refer to our API documentation to learn more about how Authentication is set up here, how Scopes work here, and also see a step-by-step explanation on how to obtain client credentials and eventually an access token here

How to Get and Use Your Access Token

Follow the steps below to get and manage your access token efficiently.

Step 1: Prepare Your Credentials

Before diving into the code, make sure you have the following credentials ready:

  • Client ID (client_id)
  • Client Secret (client_secret)
  • Organization ID (login_organization)

For details, please, refer to step 9 in the documentation here.

Step 2: Set Up Your Project

First, ensure you have Python 3 installed on your machine. You can check this by running:

python3 --version

If you don’t have Python 3, download and install it from the official Python website.

Step 3: Install Required Packages

You will need the requests package to make HTTP requests. Install it using the following command:

pip3 install requests

Step 4: Write the Code to Obtain Access Token

Create a new Python file, e.g., get_access_token.py, and open it in your code editor. Use the following code to set up the access token retrieval process:

import requests
import time

# Define the credentials and request details
CLIENT_ID = 'zzz' # Replace with your client ID
CLIENT_SECRET = 'yyy' # Replace with your client secret
LOGIN_ORGANIZATION = '123' # Replace with your login organization
TOKEN_URL = 'https://login.24sevenoffice.com/oauth/token'
AUDIENCE = 'https://api.24sevenoffice.com'

# Initialize variables for caching the token and expiration time
cached_token = None
token_expiration_time = None

# Function to obtain a new access token
def get_new_access_token():
global cached_token, token_expiration_time
body = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'audience': AUDIENCE,
'login_organization': LOGIN_ORGANIZATION
}

response = requests.post(TOKEN_URL, json=body)

if response.status_code != 200:
raise Exception(f'Failed to obtain access token: {response.text}')

data = response.json()

# Cache the token and calculate the expiration time
cached_token = data['access_token']
token_expiration_time = time.time() + (data['expires_in'] - 60) # Refresh 60 seconds before expiration

return cached_token

# Function to get the access token, using the cache if possible
def get_access_token():
global cached_token, token_expiration_time
if cached_token and time.time() < token_expiration_time:
return cached_token
return get_new_access_token()

Example Usage

You can use the following code snippet to make a sample API request using the obtained access token. This section can be copied and pasted into the same file or another file for testing.

# Define the API endpoint as a separate variable
API_ENDPOINT = 'https://rest.api.24sevenoffice.com/v1/taxes'

# Example usage
def fetch_data():
try:
token = get_access_token()

# Use the token to make an API request
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json',
}
api_response = requests.get(API_ENDPOINT, headers=headers)

if api_response.status_code != 200:
# Check for 403 Forbidden error
if api_response.status_code == 403:
print('Token may be expired or insufficient permissions. Refreshing token...')
token = get_new_access_token() # Fetch a new token

# Retry the API request with the new token
headers['Authorization'] = f'Bearer {token}'
api_response = requests.get(API_ENDPOINT, headers=headers)

if api_response.status_code != 200:
raise Exception(f'API request failed: {api_response.text}')

data = api_response.json()
print('Data:', data)

except Exception as error:
print('Error:', str(error))

# Run the fetch_data function for testing
fetch_data()

Running the Code

To execute your code, run the following command in your terminal:

python get_access_token.py

Make sure to replace the placeholder values for CLIENT_IDCLIENT_SECRET, and LOGIN_ORGANIZATION with your actual credentials before running the code.

 

With this code in place, you’ll never have to worry about expired tokens interrupting your API calls. The code handles token expiration seamlessly, making your integration with the 24SevenOffice API smooth and reliable.