Sub topic 5
Requesting an Access Token from Your My Domain
This chapter covers the single HTTP call that turns your External Client App credentials into a bearer token. It also covers what that call depends on and how it fails.
Prerequisites assumed: you have created an External Client App with the client credentials flow enabled and a run-as user assigned (earlier chapters), you know the agent ID, and you can read short Python and curl examples. You should also know what an OAuth 2.0 access token is.
Why the token request goes to your My Domain
The Agent API itself lives at api.salesforce.com. The token does not come from there. You request it from your org's My Domain URL, for example https://mycompany.my.salesforce.com. The org that issues the token is the same org whose agent you are calling.
Three values drive the request:
| Value | Where it comes from | Sent as |
|---|---|---|
| My Domain URL | Setup, My Domain | Base of the request URL |
| Consumer key | External Client App OAuth settings | `client_id` |
| Consumer secret | External Client App OAuth settings | `client_secret` |
The token endpoint path is always /services/oauth2/token. For the client credentials flow, the request is a POST with a form-encoded body (application/x-www-form-urlencoded), not JSON. This is a common first mistake. The requests library sets the right content type when you pass a dictionary to data=, and it sets a JSON content type if you use json=.
The request
Keep the consumer key and secret out of your source code. This example reads them from environment variables.
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"]Points worth noting in this code:
grant_typemust be exactlyclient_credentials.timeout=30stops the call from hanging forever. Always set a timeout on network calls.raise_for_status()turns 4xx and 5xx responses into exceptions, so a failed login does not silently continue with a missing token.SF_MY_DOMAINhas no trailing slash. A trailing slash produces a double slash in the URL, which can cause a failure that is hard to spot.
The equivalent curl command is useful for checking your configuration before you write any code:
curl -s -X POST "$SF_MY_DOMAIN/services/oauth2/token" \
-d "grant_type=client_credentials" \
-d "client_id=$SF_CLIENT_ID" \
-d "client_secret=$SF_CLIENT_SECRET"Each -d flag adds a form field, and curl sets the form content type for you.
Reading the response
A successful response is JSON. The fields you care about are:
| Field | Meaning |
|---|---|
| `access_token` | The bearer token to send on every Agent API call |
| `token_type` | Normally `Bearer` |
| `instance_url` | The org's instance URL |
| `scope` | The scopes granted to this token |
| `api_instance_url` | The API host the token is meant for, when returned |
The exact set of fields can vary by org and API version, so read only the ones you need and ignore the rest. The client credentials flow does not return a refresh token. When the token expires, you request a new one with the same call.
Note the scope field. If the Agent API scopes you configured on the External Client App do not appear there, later calls will be rejected. Check that the scopes on the app include the ones required for the Agent API, as set up in the External Client App chapter.
Using the token
Every Agent API call carries the token in an Authorization header:
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}Note the difference between the two requests. The token request is form-encoded and has no Authorization header. The Agent API requests are JSON and need the bearer token. Mixing these up is the second most common mistake.
Run-as user and what the token represents
With the client credentials flow, there is no human login. Salesforce issues the token on behalf of the run-as user you assigned to the External Client App. Anything the agent does through this token is limited by that user's permissions. If the token request succeeds but agent actions later fail on access checks, look at the run-as user's permission sets before you look at your code.
Caching and expiry
A token is valid for a limited time. The lifetime is controlled by the org's session and token settings, so do not hard-code a number. Requesting a new token for every message wastes calls and can run into rate limits. A small cache avoids this:
import time
_token = None
_expires_at = 0.0
def cached_token(lifetime_seconds: int = 1500) -> str:
global _token, _expires_at
if _token is None or time.time() >= _expires_at:
_token = get_access_token()
_expires_at = time.time() + lifetime_seconds
return _tokenThe lifetime_seconds value here is a conservative guess that is deliberately shorter than the real lifetime. If you choose it too long, you will send an expired token and get a 401. Handling that case with a retry is covered in the error handling chapter. Keep the token in memory only. Do not write it to logs or to disk.
Common errors
Salesforce reports token failures as JSON with error and error_description fields. Print the body when the call fails, because the description usually names the cause.
| Symptom | Likely cause | What to check |
|---|---|---|
| `invalid_client_id` | Wrong consumer key, or the app is not yet available in the org | Copy the key again. Confirm the app is deployed to this org |
| `invalid_client` | Wrong consumer secret | Regenerate or copy the secret again |
| `unsupported_grant_type` | Client credentials flow not enabled on the app | Enable the flow in the app's OAuth settings |
| `invalid_grant` with a message about no client credentials user | No run-as user assigned | Set the run-as user on the app |
| `invalid_request` | Body sent as JSON, or a required field is missing | Use form encoding and check all three fields |
| 404 or an HTML page | Wrong host, or a typo in the My Domain URL | Confirm you are using the My Domain, not `api.salesforce.com` |
| Connection errors | Network egress blocked or a proxy in the way | Test with curl from the same machine |
Exact error text can differ between orgs and releases, so treat the table as a guide to the category of the problem. A newly created or changed app can also take a few minutes before it is usable, so a failure right after setup may clear on its own.
The following helper shows the failure body instead of just the status code:
def get_access_token_verbose() -> 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,
)
if not response.ok:
# The body contains error and error_description, never the secret
raise RuntimeError(f"Token request failed ({response.status_code}): {response.text}")
return response.json()["access_token"]Edge cases
- Sandbox and production use different domains. A sandbox My Domain contains
sandboxin its hostname. Credentials from one org do not work against another. - Environment mismatch. If your code reads
SF_MY_DOMAINfrom one place and the agent ID from another, you can end up requesting a token from one org and calling an agent in a different one. - Clock and caching bugs. If tokens "randomly" stop working, check that your cache expiry is shorter than the real token lifetime.
- Multiple processes. Each process or container that caches its own token will make its own token request. That is normally fine, but at high scale a shared cache avoids bursts.
Exercise
Your token request returns an invalid_request error. The code uses requests.post(url, json={"grant_type": "client_credentials", "client_id": ..., "client_secret": ...}). What is the likely cause, and what is the fix?
Show answer
The token endpoint expects a form-encoded body, but json= sends a JSON body. Change json= to data= so requests sends application/x-www-form-urlencoded.
Exercise
The token request succeeds, but your cached token causes 401 responses from the Agent API about half an hour later. Name the cause and two ways to avoid it.
Show answer
The cached token outlived its real lifetime. Set the cache expiry shorter than the token lifetime, and retry once with a fresh token when a call returns 401. The retry is covered in the error handling chapter.
Exercise
Why does the token request go to your My Domain while the session calls go to api.salesforce.com?
Show answer
The token must be issued by the org that owns the External Client App and the agent, and that org is identified by its My Domain. The Agent API is served from a shared API host, and it accepts the token to identify the org and the run-as user.