Building a Python script to pull WEM adherence metrics overnight. It runs as a background service with no user interaction. Should I use Client Credentials or Authorization Code grant for the /api/v2/oauth/token call? The goal is to keep the token valid for long-running batch jobs without manual refresh.
Cause:
You’re trying to force a human-centric flow into a machine cess. Authorization Code requires a user to log in, approve scopes, and refresh tokens manually. That’s a recipe for failure in a background service. The token expires, the user isn’t there, the job fails. For server-to-server background tasks, Client Credentials is the only logical choice. It doesn’t care about users. It cares about the application identity.
Solution:
Use the Client Credentials grant. You’ll need to create a Service Account in Genesys Cloud Admin, assign it the wem:analytics:read scope (or broader WEM scopes if you need more), and grab the client ID and secret. Then hit the token endpoint with Basic Auth encoding of those credentials.
Here’s how the Python request looks using requests. Note the grant_type is client_credentials.
import requests
import base64
# Replace with your actual values
client_id = "your-client-id"
client_secret = "your-client-secret"
domain = "api.mypurecloud.com"
# Create Basic Auth header
credentials = f"{client_id}:{client_secret}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()
url = f"https://{domain}/oauth/token"
headers = {
"Authorization": f"Basic {encoded_credentials}",
"Content-Type": "application/x-www-form-urlencoded"
}
data = {
"grant_type": "client_credentials"
}
response = requests.post(url, headers=headers, data=data)
if response.status_code == 200:
token_data = response.json()
access_token = token_data["access_token"]
expires_in = token_data["expires_in"]
print(f"Token valid for {expires_in} seconds")
# Now use access_token to call WEM API
wem_headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
# Example WEM call
wem_url = f"https://{domain}/api/v2/wem/schedules/adherencereports"
wem_response = requests.get(wem_url, headers=wem_headers)
else:
print(f"Failed to get token: {response.text}")
Keep in mind the token lasts 1 hour. Your script needs to check expires_in and refresh before it hits zero. Don’t wait until it’s dead.