Sub topic 1
What the Agent API Is and When to Use It
The Agent API lets an external application communicate with an Agentforce agent over HTTP. Your application authenticates, creates a session, sends messages, reads replies, and ends the session.
This is different from using an agent through a Salesforce channel, such as a website or messaging channel. A channel manages the user interface and much of the conversation transport. The Agent API gives your system direct control. Use it when a custom application, backend service, or integration must start conversations and process replies itself.
Prerequisites
Assume that you understand REST methods, JSON, and OAuth 2.0 access tokens. You also need a Salesforce org with Agentforce enabled and an agent already built.
Prepare the Agent
Activate the agent before calling it. In Agent Builder or the relevant Salesforce setup area, confirm that the agent is active. Copy its agent ID. The ID identifies the agent in session URLs and is not the same as a display name.
An external application needs an External Client App. Configure the app for the OAuth client credentials flow. Add the narrowest API scopes that allow the application to call the Agent API. Assign a run-as user with the permissions and data access the agent requires. The agent acts with this user's Salesforce access, so choose the user carefully.
Client Credentials and Access Tokens
The client credentials flow authenticates the application itself. The application sends its client ID and secret to your Salesforce My Domain token endpoint. Salesforce returns a short-lived access token. The token represents the configured run-as user when the application calls the Agent API.
Keep the client secret on a server. Never place it in browser code or source control.
import os
import requests
domain = os.environ["SF_MY_DOMAIN"]
response = requests.post(
f"{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()
access_token = response.json()["access_token"]The next step is sending this token in an Authorization: Bearer header when creating an agent session.
Exercise
Why should the run-as user have only the permissions needed by the agent?
Show answer
Every API call can operate with that user's access, so limiting permissions reduces the impact of a stolen token or misconfigured agent.