Batch job fails with 401 after access token expires mid-run

I’ve got a Python script that pulls adherence data for our WFM reports. It grabs a token at the start, but the job runs for 45 minutes. The token only lasts 30.

Around row 400, the API call to /api/v2/wf/outcomes starts returning 401 Unauthorized. I’m not sure how to handle the refresh logic inside the loop without breaking the batch.

requests.get(url, headers={'Authorization': f'Bearer {token}'})

Does the Python SDK auto-refresh, or do I need to write a wrapper?

Hardcoding the token in the header is a recipe for disaster when dealing with long-running batch jobs. Access tokens in Genesys Cloud expire after 30 minutes by default. You can’t just keep sending the same Bearer token and expect it to work.

The standard approach here isn’t to manually parse the expires_in claim and set a timer. That’s fragile. Instead, use the official Genesys Cloud Python SDK (genesys-cloud-sdk). It handles the OAuth client credentials flow and token refresh internally. When the SDK detects an expired token during an API call, it automatically fetches a new one using your client ID and secret, then retries the request. You don’t need to write the refresh logic yourself.

Here’s how you’d set it up:

from platformclientv2 import Configuration, WfOutcomesApi
from platformclientv2.rest import ApiException

# Initialize config with your client credentials
config = Configuration(
 host='https://api.mypurecloud.com',
 client_id='your_client_id',
 client_secret='your_client_secret',
 oauth_client_credentials=True
)

# Create the API instance
wf_outcomes_api = WfOutcomesApi(config.api_client)

try:
 # This call will automatically refresh the token if it expires
 outcomes = wf_outcomes_api.get_wf_outcomes()
 for outcome in outcomes.entities:
 process_outcome(outcome)
except ApiException as e:
 print(f"Exception when calling WfOutcomesApi: {e}")

This way, your script runs for hours if needed. The SDK manages the session. If you’re stuck with raw requests for some reason, you’d need to wrap your calls in a retry function that catches 401s, calls the /api/v2/oauth/token endpoint with your client credentials to get a fresh token, and then retries the original request exactly once. But why reinvent the wheel? The SDK exists for this. Just switch to the SDK and stop managing tokens manually.