Sub topic 1
What the Pub/Sub API Is and When to Use It
Prerequisites
This chapter assumes that you understand Salesforce orgs, objects, connected apps or external client apps, OAuth 2.0 access tokens, and basic publish/subscribe messaging. You should also be comfortable reading Python.
What the Pub/Sub API Does
The Salesforce Pub/Sub API is a gRPC interface for receiving Salesforce events. It provides one client model for platform events, Change Data Capture (CDC) events, and real-time event monitoring events.
Choose it when an external service needs a controlled, high-throughput event stream. The API lets your client discover event schemas, request a specific number of events, and resume after a disconnect by using replay IDs.
Compared with older Salesforce streaming options, Pub/Sub API uses protocol buffers and gRPC rather than a REST or CometD-based client. This makes bidirectional streaming and explicit flow control part of the normal client design.
Topics and Event Types
A topic is a named event stream. Common topic categories include:
- Platform event topics, for custom business events.
- CDC topics, for record changes such as creates, updates, and deletes.
- Real-time event monitoring topics, for selected activity and security events.
The topic determines the event schema and whether subscription is supported. Use GetTopic before subscribing so the client can verify these details.
gRPC and Generated Stubs
gRPC uses a service definition in a .proto file. The Salesforce pubsub_api.proto file defines messages such as TopicRequest and FetchRequest, plus the PubSub service. A code generator turns that definition into client stubs, which are language-specific classes for making RPC calls.
python -m pip install grpcio grpcio-tools
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. pubsub_api.protoThe generated modules provide the request classes and PubSubStub used by a Python client.
Authentication Metadata
After obtaining an OAuth access token, attach these gRPC metadata headers to each call:
def auth_metadata(access_token, instance_url, tenant_id):
return (
("accesstoken", access_token),
("instanceurl", instance_url),
("tenantid", tenant_id),
)
metadata = auth_metadata(
"00D-example-token",
"https://example.my.salesforce.com",
"00Dxx0000000001",
)
print(metadata)The token authorizes the request. The instance URL identifies the Salesforce org, and the tenant ID identifies that org for Pub/Sub routing.
Exercise
Which API feature lets a subscriber limit how many events Salesforce sends?
Show answer
The subscriber uses num_requested in a FetchRequest to control delivery.