Hey folks,
I’ve got a Python script that runs every morning at 7am Central to pull WFM adherence data. It queries the /api/v2/analytics/wfm/adherence/details/query endpoint in a loop to get all the agents. The problem is the batch size is large, so the script takes about 45 minutes to finish. The access token I grab at the start only lasts for an hour, but it seems to expire right around the 30-minute mark sometimes? Or maybe the clock is off on my server.
Anyway, the script starts fine. It pulls the first 100 agents. Then it loops. Suddenly I get a 401 Unauthorized error and the whole thing crashes. I don’t want to re-auth for every single request because that’s slow and annoying. I just want it to auto-refresh if it fails.
Here’s the basic loop I’m using:
import requests
token = get_initial_token() # works fine
headers = {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'}
for agent_id in agent_list:
url = f'https://myorg.mypurecloud.com/api/v2/analytics/wfm/adherence/details/query?agentIds={agent_id}'
response = requests.get(url, headers=headers)
if response.status_code == 401:
print("Token expired, need to refresh")
# what do I put here?
else:
save_data(response.json())
I’m using the client_credentials grant since this is a service account. I have the client ID and secret. I’m not sure if I should be using a refresh token or just getting a new access token with the client secret again? The docs are a bit vague on the exact flow for long-running scripts.
If I just call the token endpoint again with the client secret, does that invalidate the old token? Or can they coexist? I tried calling it again in the if block but I’m not sure if I’m doing it right. Any help on the logic would be great. I just want the script to keep running without me having to watch it.