Sub topic 6
Publishing events through the REST API
This chapter assumes you can define a platform event with custom fields, you know what a Salesforce access token is, and you can read an HTTP request. It covers how an external system publishes a platform event over REST, how to read the response, and what goes wrong in practice.
Why publish through REST
Apex and flows publish from inside Salesforce. An external system, such as an order management service, a warehouse app, or a middleware tool, has no access to EventBus.publish. It needs an HTTP endpoint instead.
Salesforce exposes platform events through the same REST API that handles other records. A platform event is a kind of sObject. You publish one by creating a record of the event's API name. No special endpoint is involved.
The record is not saved to the database. Salesforce accepts it and places it on the event bus, where subscribers receive it. You cannot query it with SOQL, update it, or delete it afterward.
The request
The endpoint follows the standard sObject pattern:
POST /services/data/v60.0/sobjects/Order_Shipped__e/
Authorization: Bearer <access_token>
Content-Type: application/json
{
"Order_Number__c": "00012345",
"Status__c": "Shipped"
}Each part has a job:
- The host. Send the request to your org's instance or My Domain URL, for example
https://mycompany.my.salesforce.com. The request line above shows only the path. - The version.
v60.0is the API version. Use a version your org supports. - The object name.
Order_Shipped__eis the event's API name. The__esuffix marks a platform event. - The header.
Authorization: Bearercarries an OAuth access token. Obtain it through whichever OAuth flow your integration uses. - The body. JSON keys are field API names. Include the custom fields you defined. Do not send
Id,ReplayId, orCreatedDate, because Salesforce sets them.
The response
A successful call returns HTTP 201 and a JSON body:
{
"id": "e00xx0000000001AAA",
"success": true,
"errors": []
}The id begins with the event's key prefix. It identifies the published message. It is not a record you can look up later.
Treat success: true as the same signal as isSuccess() on the SaveResult returned by EventBus.publish in Apex. It means Salesforce accepted the event for publishing. It does not mean any subscriber has run, and it does not mean a subscriber succeeded. Delivery to subscribers happens afterward and independently.
Publish behavior for REST calls
Earlier you chose between publish after commit and publish immediately. That setting matters most when Apex publishes in the middle of a transaction.
A REST call to the event endpoint is its own request. It has no surrounding transaction to roll back. The event is accepted once the call succeeds, and a failed call publishes nothing. You do not need to coordinate with a commit.
A runnable client
This Python script gets no token by itself. It reads the instance URL and token from environment variables, so you can supply them from your own OAuth flow.
import os
import requests
instance_url = os.environ["SF_INSTANCE_URL"]
access_token = os.environ["SF_ACCESS_TOKEN"]
url = f"{instance_url}/services/data/v60.0/sobjects/Order_Shipped__e/"
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json",
}
payload = {"Order_Number__c": "00012345", "Status__c": "Shipped"}
response = requests.post(url, json=payload, headers=headers, timeout=30)
if response.status_code == 201 and response.json().get("success"):
print("Published event", response.json()["id"])
else:
print("Publish failed", response.status_code, response.text)Never hard-code the token in the script. Tokens expire, so a long-running integration must refresh them.
Publishing several events in one call
Calling the endpoint once per event is simple but costs one API request each. To send many events, use the composite endpoint, which accepts a list of records of one type:
POST /services/data/v60.0/composite/sobjects
Authorization: Bearer <access_token>
Content-Type: application/json
{
"allOrNone": false,
"records": [
{
"attributes": { "type": "Order_Shipped__e" },
"Order_Number__c": "00012345",
"Status__c": "Shipped"
},
{
"attributes": { "type": "Order_Shipped__e" },
"Order_Number__c": "00012346",
"Status__c": "Shipped"
}
]
}The response is an array with one result per record, in the same order as the request. With allOrNone set to false, one bad record does not block the others, so check every element. With true, a single failure causes the whole batch to fail.
Batching reduces API calls. It does not bypass event publishing limits. Each event still counts toward your hourly publishing allocation.
Errors and what to do about them
| Status | Typical cause | What to do |
|---|---|---|
| 400 | Malformed JSON, a field that does not exist, a value of the wrong type, or a missing required field | Fix the payload. Retrying the same body will fail again. |
| 401 | Expired or invalid access token | Refresh the token and retry once. |
| 403 | The user lacks create access to the event, or a limit was exceeded | Check permissions. If a limit is the cause, back off. |
| 404 | The event name or API version is wrong | Check the `__e` API name. |
| 5xx | A temporary server problem | Retry with exponential backoff. |
Two details are easy to miss.
First, the integration user needs create permission on the event object. Grant it through a permission set on the platform event's object permissions. Without it, a valid token still gets a 403.
Second, an HTTP 2xx status is not enough in batch calls. A composite response can return HTTP 200 while individual records inside it report success: false. Always inspect each result.
Retries and duplicates
Network failures create a hard case. If a request times out, you do not know whether Salesforce accepted the event. Retrying may publish it twice.
Platform events have no built-in deduplication for REST publishers. Design for this:
- Include a unique business key in the event, such as an
Event_Key__cfield with a UUID that the publisher generates once per logical event. - Make the subscriber idempotent. Before creating a record, check whether one already exists for that key.
- Reuse the same key on every retry of the same event.
This approach accepts that delivery may repeat, and it makes repetition harmless.
Limits to remember
Several limits affect REST publishing:
- Each org has an allocation of events it can publish per hour and per day. The exact numbers depend on your edition and any add-ons. Check them in Setup or through the
/limitsREST resource instead of assuming a figure. - Each event has a maximum size, and field values count toward it.
- Each API call counts toward the org's daily API request limit, so batching saves that allocation.
When a limit is exceeded, publishing fails with an error. Treat it as a signal to slow down, not to retry immediately.
GET /services/data/v60.0/limits
Authorization: Bearer <access_token>The response lists remaining and maximum values for several allocations, including platform event usage. Check the entries that mention events.
Verifying the result
Publishing does not store a record, so you cannot confirm delivery by querying. Use these checks instead:
- Subscribe a Lightning Web Component or a debug trigger and watch for the event.
- Add a trigger that logs
Trigger.newwithSystem.debug, then read the debug log. - Check the published-event usage in the org's event monitoring tools.
A subscriber that creates a visible record, such as the Task from the earlier trigger example, gives the quickest confirmation during development.
Summary of decisions
- Use the single-record endpoint for low volume and simple code.
- Use the composite endpoint when you send events in bursts.
- Add a unique key to every event that must not be processed twice.
- Give the integration user the minimum permission needed: create access on the specific event.
Exercise
Your integration posts an event and the request times out with no response. You retry, and later find that the subscriber created two Tasks for the same order. What caused the duplicate, and what two changes prevent it?
Show answer
The first request probably reached Salesforce and was accepted, but the response was lost, so the retry published a second event. Platform events have no deduplication for REST publishers. Prevent it by adding a unique key field that the publisher generates once and reuses on every retry, and by making the subscriber trigger idempotent, so it skips creating a Task when one already exists for that key.
Exercise
A composite request with allOrNone set to false returns HTTP 200. Can you assume every event was published? What should the client do?
Show answer
No. The HTTP status describes the whole request, not each record. The client must read the result array, which is in request order, and check the success value of every element. It should retry only the failed records, and only after deciding whether the error is permanent, as with a 400-type validation error, or temporary.