Python requests OAuth2 client credentials returning 401

What’s the correct way to handle the form data for the client credentials grant in Python?

I’m writing a quick script to grab an access token for some internal API calls. I’ve got the client ID and secret in environment variables. Here’s the snippet I’m using:

import requests
import os

auth_url = "https://api.mypurecloud.com/oauth/token"

payload = {
 "grant_type": "client_credentials",
 "client_id": os.getenv("GENESYS_CLIENT_ID"),
 "client_secret": os.getenv("GENESYS_CLIENT_SECRET")
}

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

I keep getting a 401 Unauthorized. The error message says invalid_client. I’ve triple-checked the env vars and they match what’s in the developer portal. I thought maybe I needed to pass the client ID in the header instead of the body, but the docs show it in the form data.

Is there a specific Content-Type header I’m missing? I assumed application/x-www-form-urlencoded is the default for data= in requests. The script hangs for a second then fails. Any ideas what I’m doing wrong here?

Use requests.post with the data parameter, not json. The OAuth endpoint expects application/x-www-form-urlencoded. Passing JSON triggers a 401 because the server can’t parse the credentials. Swap json=payload to data=payload and it works.