OAuth2 Client Credentials token request returning 401 in Python

Attempting to automate API calls for our CX-as-Code pipelines using Python requests. The goal is to fetch an OAuth2 access token via Client Credentials flow. The endpoint is https://api.mypurecloud.com/oauth/token. Sending a POST with grant_type=client_credentials and the credentials in the Authorization header. Getting a 401 Unauthorized response. The base64 encoding seems correct. Can you spot the issue in this snippet?

import requests, base64
creds = f"{client_id}:{client_secret}"
headers = {"Authorization": f"Basic {base64.b64encode(creds.encode()).decode()}", "Content-Type": "application/x-www-form-urlencoded"}
resp = requests.post(url, data={"grant_type": "client_credentials"}, headers=headers)

Check your base64 encoding. Python’s base64.b64encode returns bytes, so you’ll need to decode to string first. Also, ensure the client ID and secret match an app with the correct scopes. Here’s the quick fix for the header:

import base64, requests
creds = f"{client_id}:{client_secret}"
encoded = base64.b64encode(creds.encode()).decode('utf-8')
headers = {"Authorization": f"Basic {encoded}"}
r = requests.post("https://api.mypurecloud.com/oauth/token", data={"grant_type": "client_credentials"}, headers=headers)

Verify the app permissions in the developer console.