Access token expires mid-batch during bulk user export

Hey everyone. Running into a weird issue with my Python script that pulls user data from Genesys Cloud. It’s been working fine for months, but recently started failing halfway through large batches. The script grabs an initial access token, then loops through pages of users. About 10 minutes in, the token expires. The next API call throws a 401, and the whole job crashes because the retry logic isn’t catching it properly.

Here’s the basic flow:

import requests
from genesyscloud.auth import AuthClient

auth = AuthClient(client_id, client_secret)
auth.login()
token = auth.get_access_token()

headers = {'Authorization': f'Bearer {token}'}

for page in range(1, 100):
 resp = requests.get(f'https://api.mypurecloud.com/api/v2/users?page_size=50&page_number={page}', headers=headers)
 if resp.status_code == 401:
 # refresh logic here
 pass
 else:
 process_data(resp.json())

The problem is that AuthClient doesn’t automatically refresh the token in the background for long-running scripts. I’m manually calling auth.login() again when I catch the 401, but it feels hacky. Also, the first request after refresh sometimes still fails with a 401, like there’s a race condition or the token isn’t ready yet.

I’ve seen people mention using a token cache or a wrapper class, but I’m not sure how to implement that cleanly without blocking the main thread. Is there a recommended pattern for handling token expiry in bulk operations? Maybe using a specific SDK method I’m missing?

Also, wondering if the refresh_token grant type is better suited here than client credentials, since the job runs unattended. But switching flows seems like a bigger lift. Any thoughts on how to keep the token fresh without disrupting the batch process?