Sub topic 6
Finding a Topic's Schema with GetTopic and GetSchema
This chapter shows how to learn what an event looks like before you subscribe to it. You call two RPCs in order. GetTopic tells you whether a topic can be subscribed to and which schema it uses. GetSchema returns that schema as JSON.
Prerequisites
This chapter assumes you have:
- Generated Python stubs from
pubsub_api.proto(pubsub_api_pb2andpubsub_api_pb2_grpc). - An OAuth 2.0 access token, the org's instance URL, and the tenant ID, as covered in the authentication chapter.
- A basic idea of what a platform event or Change Data Capture (CDC) event is.
Why discovery comes first
Pub/Sub API events arrive as binary Avro. Avro is a compact format that carries no field names in the bytes. Without the schema, the payload is unreadable. The schema is the list of fields, their types, and their order.
The event message carries only a schema ID. It does not carry the schema itself. So a subscriber needs a way to turn a schema ID into a schema. The API gives you two steps for this:
GetTopictakes a topic name and returns topic metadata, including a schema ID.GetSchematakes a schema ID and returns the schema definition.
Calling GetTopic
A topic name is a path-like string. Typical examples:
/event/Order_Shipped__efor a custom platform event./data/AccountChangeEventfor CDC on Account./data/ChangeEventsfor the combined CDC channel.
Every call needs the three metadata headers: accesstoken, instanceurl, and tenantid. Send them on each RPC, not once per channel.
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
ENDPOINT = "api.pubsub.salesforce.com:7443"
def auth_metadata(access_token, instance_url, tenant_id):
return (
("accesstoken", access_token),
("instanceurl", instance_url),
("tenantid", tenant_id),
)
def describe_topic(access_token, instance_url, tenant_id, topic_name):
with grpc.secure_channel(ENDPOINT, grpc.ssl_channel_credentials()) as channel:
stub = pb2_grpc.PubSubStub(channel)
metadata = auth_metadata(access_token, instance_url, tenant_id)
topic = stub.GetTopic(pb2.TopicRequest(topic_name=topic_name), metadata=metadata)
print("can_subscribe:", topic.can_subscribe, "schema_id:", topic.schema_id)
return topic.schema_idThe function opens a TLS channel, builds the stub, calls GetTopic, prints two fields, and returns the schema ID.
Fields worth reading
The TopicInfo response has more fields than the two printed above. The ones you will use most:
| Field | Meaning |
|---|---|
| `topic_name` | The name you asked for, echoed back. |
| `can_subscribe` | `True` if you may subscribe to this topic. |
| `can_publish` | `True` if you may publish to this topic. |
| `schema_id` | The ID of the schema for events on this topic. |
| `rpc_id` | An identifier for the call, useful when you contact support. |
Check can_subscribe before you open a stream. A topic can exist and still be closed to you because of permissions. For example, a user without access to the object behind a CDC topic will see False, or get an error instead.
Calling GetSchema
GetSchema takes the schema ID and returns a SchemaInfo message. Its schema_json field holds an Avro schema as a JSON string. Parse it with json.loads, then hand it to fastavro.parse_schema.
import json
import fastavro
import pubsub_api_pb2 as pb2
schema_cache = {}
def get_schema(stub, metadata, schema_id):
if schema_id not in schema_cache:
info = stub.GetSchema(pb2.SchemaRequest(schema_id=schema_id), metadata=metadata)
schema_cache[schema_id] = fastavro.parse_schema(json.loads(info.schema_json))
return schema_cache[schema_id]This is the lookup used by the decoder in the next chapter. It makes one network call per schema ID and then serves repeat lookups from memory.
What a schema looks like
A schema for a custom platform event is a record with a name, a namespace, and a list of fields. The exact content depends on your event. A trimmed example looks like this:
example_schema = {
"type": "record",
"name": "Order_Shipped__e",
"namespace": "com.sforce.eventbus",
"fields": [
{"name": "CreatedDate", "type": "long"},
{"name": "CreatedById", "type": "string"},
{"name": "Order_Number__c", "type": ["null", "string"], "default": None},
],
}Two details matter here:
- Standard header fields such as
CreatedDateandCreatedByIdcome with every platform event, alongside your custom__cfields. - Fields that can be empty use a union type like
["null", "string"]. After decoding, such a field is eitherNoneor a value.
CDC schemas are larger. They include a ChangeEventHeader record, which holds the entity name, the change type, the record IDs, and a list of changed fields. The CDC chapter covers it in detail.
Why you cache schemas by ID
The schema ID is a fingerprint of the schema content. If the same ID comes back, the schema is the same. This is why caching by ID is safe and why you should do it.
- Each event message includes its own
schema_id. If you calledGetSchemafor every event, you would add a round trip to every message and waste your request budget. - When someone changes the event definition (for example, adds a field to a platform event), new events carry a new schema ID. Your cache misses on that ID, you fetch the new schema, and decoding continues.
This means you do not need to restart the subscriber when a field is added. Read the schema ID from each event, not from the GetTopic call you made at startup.
Putting the two calls together
A small helper that discovers a topic and returns a ready parsed schema:
import grpc
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
def discover(access_token, instance_url, tenant_id, topic_name):
metadata = (
("accesstoken", access_token),
("instanceurl", instance_url),
("tenantid", tenant_id),
)
with grpc.secure_channel("api.pubsub.salesforce.com:7443",
grpc.ssl_channel_credentials()) as channel:
stub = pb2_grpc.PubSubStub(channel)
topic = stub.GetTopic(pb2.TopicRequest(topic_name=topic_name), metadata=metadata)
if not topic.can_subscribe:
raise PermissionError(f"Cannot subscribe to {topic_name}")
schema = stub.GetSchema(pb2.SchemaRequest(schema_id=topic.schema_id), metadata=metadata)
return topic.schema_id, schema.schema_json
if __name__ == "__main__":
import os
schema_id, schema_json = discover(
os.environ["SF_ACCESS_TOKEN"],
os.environ["SF_INSTANCE_URL"],
os.environ["SF_TENANT_ID"],
"/event/Order_Shipped__e",
)
print(schema_id)
print(schema_json)Run it with the three environment variables set. It prints the schema ID and the raw schema JSON. Seeing the JSON once by hand is a good way to learn what your topic really contains.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `UNAUTHENTICATED` status | Missing, expired, or malformed `accesstoken`, or a wrong `instanceurl` or `tenantid`. | Refresh the token and check all three headers. |
| `INVALID_ARGUMENT` or `NOT_FOUND` on `GetTopic` | The topic name is misspelled, has the wrong prefix, or the event does not exist in this org. | Check the exact API name, including the `__e` suffix and the `/event/` or `/data/` prefix. |
| `can_subscribe` is `False` | The user lacks permission, or CDC is not enabled for the object. | Grant access, or enable change events for the object in Setup. |
| `NOT_FOUND` on `GetSchema` | A stale or incorrect schema ID. | Take the ID from `GetTopic` or from an event, not from a stored copy. |
| Decoding gives wrong values | The wrong schema was used for the bytes. | Look up the schema by the event's own `schema_id`. |
Design notes
- Discovery calls are cheap and run once per topic at startup, plus once per new schema ID. They do not belong in the event loop.
- You can persist the schema cache to disk if startup latency matters. Because IDs are content fingerprints, a stored schema never goes stale for its ID.
- On a reconnect, reuse the in-memory cache. You only need
GetTopicagain if you want to re-checkcan_subscribe.
Exercise
Your subscriber has run for a week. An admin adds a field to the platform event. The subscriber starts to produce garbled records. What did the code do wrong, and how should it be fixed?
Show answer
It decoded all events with the schema ID it received from GetTopic at startup. Events published after the change carry a new schema ID. The fix is to read schema_id from each event, call GetSchema when that ID is not in the cache, and decode with the schema that matches the event.
Exercise
Why should you check can_subscribe from GetTopic before opening a Subscribe stream, and what field from the same response do you pass to GetSchema?
Show answer
cansubscribe tells you whether the current user may receive events on the topic, so you can fail early with a clear message instead of a later stream error. You pass schemaid to GetSchema, inside a SchemaRequest.