Does anyone know why my Python script fails to retrieve an access token from the NICE CXone OAuth endpoint using the client_credentials grant type?
I am building a background integration service in Lagos, and while my HTTP requests to the /api/v2/ endpoints work fine with static tokens, automating the token refresh via Python’s requests library is failing consistently. I have verified that the client ID and secret are correct and that the scope is valid. The issue seems to lie in the payload formatting or encoding within the request body.
Here is the relevant code snippet:
import requests
import base64
client_id = "my_client_id"
client_secret = "my_client_secret"
auth_string = f"{client_id}:{client_secret}"
encoded_auth = base64.b64encode(auth_string.encode()).decode()
headers = {
"Authorization": f"Basic {encoded_auth}",
"Content-Type": "application/x-www-form-urlencoded"
}
payload = {
"grant_type": "client_credentials"
}
response = requests.post(
"https://api.mynicecx.com/oauth2/token",
data=payload,
headers=headers
)
print(response.status_code)
print(response.text)
The API returns a 400 Bad Request with the following JSON payload:
{
"error": "invalid_request",
"error_description": "Missing required parameter: grant_type"
}
I have read the documentation which states:
The request body must be URL-encoded form data. The grant_type parameter is mandatory for client credentials flows.
I am explicitly setting Content-Type to application/x-www-form-urlencoded and passing the payload via the data argument, which requests should handle correctly. I have also tried sending the payload as JSON, but that resulted in a 415 Unsupported Media Type.
Is there a specific quirk with the CXone token endpoint regarding how Python handles the form encoding, or am I missing a subtle requirement in the header configuration?