Hit a 401 Unauthorized error halfway through a batch export job. The access token expires after an hour, and the script doesn’t refresh it automatically. The job processes about 15,000 records, which takes longer than the token lifetime.
Here’s the basic flow:
def get_token():
# ... OAuth client credentials flow ...
return response.json()['access_token']
def export_data(token):
headers = {'Authorization': f'Bearer {token}'}
for i in range(15000):
response = requests.get(f'https://myapi.genesys.cloud/api/v2/analytics/users/queues/summary', headers=headers)
if response.status_code == 401:
# Token expired
break
# Process data
save_to_db(response.json())
The script crashes with a 401 after processing around 8,000 records. I know I need to implement token refresh logic, but I’m not sure the best way to handle it. Should I check the token expiry time before each request, or catch the 401 and retry with a new token?
Also, is there a standard way to get the token expiry time from the response? I see an expires_in field, but I want to make sure I’m interpreting it correctly.
Any pointers on implementing a solid token refresh mechanism for long-running jobs would be appreciated. I’ve tried wrapping the API calls in a retry loop, but it feels hacky.