Sub topic 5
Requesting an Access Token from Your My Domain
This chapter shows how to request an access token for the Agent API. It assumes you can read short Python and curl examples, know what an OAuth 2.0 access token is, and have already created an External Client App with the client credentials flow enabled. You will also need its consumer key and consumer secret, and the My Domain URL of your org.
Where the request goes
Every Agent API call needs a bearer token. You get one by sending a POST request to the token endpoint of your org's My Domain:
https://<your-domain>.my.salesforce.com/services/oauth2/tokenUse your My Domain URL, not login.salesforce.com. The client credentials flow is tied to the org that owns the External Client App, so the request must reach that org directly.
The request body is form-encoded, not JSON. It has three fields:
| Field | Value |
|---|---|
| `grant_type` | `client_credentials` |
| `client_id` | The consumer key of your External Client App |
| `client_secret` | The consumer secret of your External Client App |
No user name or password is sent. Salesforce issues the token on behalf of the run-as user you configured on the app.
A working example in Python
The function below reads the My Domain URL and credentials from environment variables, so no secret appears in the source code.
import os
import requests
MY_DOMAIN = os.environ["SF_MY_DOMAIN"] # for example https://mycompany.my.salesforce.com
def get_access_token() -> str:
response = requests.post(
f"{MY_DOMAIN}/services/oauth2/token",
data={
"grant_type": "client_credentials",
"client_id": os.environ["SF_CLIENT_ID"],
"client_secret": os.environ["SF_CLIENT_SECRET"],
},
timeout=30,
)
response.raise_for_status()
return response.json()["access_token"]Passing data= makes requests send a form-encoded body with the correct Content-Type. If you pass json= instead, the request fails. raise_for_status() turns a 4xx or 5xx reply into an exception, so a bad credential stops the program at this point instead of failing later.
Using the token
Put the token in an Authorization header on every Agent API request:
headers = {
"Authorization": f"Bearer {get_access_token()}",
"Content-Type": "application/json",
}The response also contains other fields, such as instance_url and token_type. The Agent API calls in the next chapters use a fixed API base URL, so you only need access_token here.
Common errors
invalid_client_idorinvalid_client: The consumer key or secret is wrong, or the app is not available in this org. Copy both values again from the app settings.unsupported_grant_type: The client credentials flow is not enabled on the External Client App.invalid_grant: The app has no run-as user, or the run-as user cannot be used. Check the app's policies.- Request goes to the wrong host: A request to
login.salesforce.comor to another org's domain does not find your app. CheckSF_MY_DOMAIN. KeyErroron an environment variable: One of the three variables is not set in the shell that runs the script.
Token lifetime
The token expires after a period set by your org's session settings. The client credentials flow does not return a refresh token. When a token expires, you request a new one with the same call. A later chapter covers how to detect expiry and retry.
Exercise
Your token request returns an unsupported_grant_type error. The consumer key and secret are correct. What should you check first, and why must the request body be sent as data= rather than json= in Python's requests?
Show answer
Check that the client credentials flow is enabled on the External Client App. The token endpoint expects a form-encoded body, and data= sends it that way, while json= sends a JSON body that the endpoint does not accept.