Stats API returning 401 despite valid OAuth token

Trying to pull real-time queue stats via /api/v2/analytics/queues/realtime. The script uses a valid Bearer token for other endpoints, but this one keeps throwing a 401 Unauthorized. Here’s the snippet:

resp = requests.get('https://api.mypurecloud.com/api/v2/analytics/queues/realtime', headers={'Authorization': f'Bearer {token}'})
print(resp.status_code)

Docs say this endpoint requires specific scopes, but I’ve granted everything. What’s missing?

The issue is almost certainly the scope on that token. Analytics endpoints are stricter than most. You need analytics:read specifically. If you’re using client_credentials, make sure that scope is in the request body. If you’re using authorization_code, the user needs the permission in their role.

Also, check the environment. api.mypurecloud.com is the old EU endpoint. If your org is in US or another region, you’ll get a redirect or a 401 depending on how your client handles it. Use api.us.genesyscloud.com or check api.genesyscloud.com for region-aware .

Here’s how to debug it properly:

import requests

# 1. Verify the token actually has the right scope
# This endpoint returns the scopes granted to the current token
token_info = requests.get('https://api.genesyscloud.com/oauth2/me', headers={'Authorization': f'Bearer {token}'})
print("Token scopes:", token_info.json().get('scope'))

# 2. Make sure 'analytics:read' is in that list
# If not, re-request the token with the correct scope

# 3. Try the analytics endpoint again with the correct base URL
resp = requests.get('https://api.genesyscloud.com/api/v2/analytics/queues/realtime', headers={'Authorization': f'Bearer {token}'})
print(resp.status_code)
print(resp.text)

If analytics:read is missing, you’ll get a 401. No amount of retrying will fix that. The token just doesn’t have the key.

Also, watch out for token expiration. If you’re caching tokens for longer than their lifetime, you’ll start seeing 401s randomly. Check the expires_in field in the token response.

One more thing: if you’re using a service account, make sure it’s assigned a role that includes analytics permissions. Just having the scope in the request isn’t enough if the role doesn’t allow it.

Check the response body too. Sometimes it tells you exactly what’s wrong.

is spot on about the scope. Just adding that you’ll need analytics:read in your token. Also, double-check the region endpoint. api.mypurecloud.com is EU. If you’re on US East, hit api.us-east-1.mygenesys.com. Wrong host kills the auth handshake before scopes even matter.