Python requests returning 401 when trying to get OAuth2 token for Genesys Cloud

I’m trying to script a quick token refresh using Python requests so I don’t have to manually copy paste tokens from the developer portal every time. It seems straightforward enough but I’m hitting a wall with the authentication step.

The code looks like this:

import requests

url = "https://api.mypurecloud.com/oauth/token"
headers = {
 "Content-Type": "application/x-www-form-urlencoded"
}
payload = {
 "grant_type": "client_credentials",
 "client_id": "my-client-id",
 "client_secret": "my-secret"
}

response = requests.post(url, headers=headers, data=payload)
print(response.status_code)
print(response.json())

I’m getting a 401 Unauthorized error. The response body just says {"error":"invalid_client","error_description":"client authentication failed"}.

I’ve double checked the Client ID and Secret in the Genesys Cloud admin console under Integrations. They match exactly. I’m not using the SDK right now, just raw requests to understand the flow better. The endpoint URL looks correct according to the docs. I’m in London time if that matters for any caching issues but it doesn’t seem like it.

Is there something missing from the payload? I read somewhere about adding scope but the docs for client credentials don’t explicitly require it for the token request itself. I’m probably missing something obvious here.

The docs show the endpoint expects application/x-www-form-urlencoded. Using a dict in requests.post sends JSON by default. Switch to the data parameter.

payload = {"grant_type": "client_credentials", "client_id": id, "client_secret": secret}
r = requests.post(url, data=payload)

Also double check your client credentials.