Python requests OAuth2 token failing with 401

Is there a specific header requirement I’m missing for the Genesys Cloud OAuth2 client credentials flow?

I’m hitting /oauth/token with my client_id and secret in the body, but getting a 401 back. The credentials work in Postman, so the creds are good.

Here’s the snippet:

import requests

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

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

Returns {'error': 'invalid_client'}. We’ve tried basic auth in the header too but no luck.

The docs specify application/x-www-form-urlencoded for the content type. Your payload looks correct, but Python’s requests defaults to JSON if you don’t specify otherwise, which breaks the OAuth endpoint. Try passing the dict directly to data instead of json.

response = requests.post(url, data=payload, headers={'Content-Type': 'application/x-www-form-urlencoded'})