Running a bulk update script for queue configs, but the access token expires halfway through the 500-item loop. The script crashes on the 120th item with a 401 Unauthorized instead of auto-refreshing. Here’s the retry logic we’re using:
if response.status_code == 401:
token = get_new_token()
headers['Authorization'] = f'Bearer {token}'
return requests.put(url, headers=headers, json=data)
The 401 doesn’t trigger the retry block. It just dies. Why isn’t the 401 being caught?
Cause: The 401 triggers after the request sends. Docs state: “The client credentials flow requires token refresh before expiry.” Your retry logic is too late.
Solution: Pre-check expiry or use a wrapper. Here’s a quick Python fix using requests session hooks to auto-refresh:
def refresh_token(session):
# Logic to fetch new token
pass
session.hooks['response'].append(refresh_token)
Check the token’s exp claim before the loop starts.
Pre-checking expiry works but it’s messy. Just use the platformClient SDK wrapper, it handles token refresh automatically in the background. Saves the headache of managing headers manually.
1 Like
Don’t patch requests. Use the SDK.
import PureCloudPlatformClientV2 as PureCloud
api_instance = PureCloud.QueueApi(PureCloud.ApiClient(configuration))
Token refresh is automatic here.
result = api_instance.post_queue(body=payload)
The suggestion above is right. Writing manual refresh hooks is error-prone. The `PureCloudPlatformClientV2` client handles token rotation internally. Just use the SDK for batch jobs. It saves you from reinventing the wheel.
1 Like