Sub topic 6
Finding a topic's schema with GetTopic and GetSchema
This chapter assumes you have a working gRPC channel, generated stubs from pubsub_api.proto, and an access token with the three metadata headers (accesstoken, instanceurl, tenantid) from the previous chapters.
Why you need the schema first
Events arrive as Avro binary. The bytes carry no field names or types, so you cannot read them until you have the schema that wrote them. The Pub/Sub API gives you that schema in two calls.
GetTopicreturns facts about a topic, including the ID of its current schema.GetSchematakes that ID and returns the schema as JSON.
Step 1: GetTopic
GetTopic is a unary RPC: one request, one response. Send a TopicRequest with the topic name, such as /event/Order_Shipped__e or /data/AccountChangeEvent.
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_idTwo fields matter here:
| Field | Meaning |
|---|---|
| `can_subscribe` | Whether your user may subscribe to this topic. |
| `schema_id` | ID of the topic's current schema. |
Check can_subscribe before you open a stream. A False value means a permissions problem you can report clearly, instead of a stream that fails later.
Step 2: GetSchema and decoding
GetSchema takes a SchemaRequest with the schema_id. The response holds schema_json, an Avro schema as a JSON string. Parse it with fastavro and keep it in a dictionary keyed by ID.
import io
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]
def decode_event(stub, metadata, producer_event):
schema = get_schema(stub, metadata, producer_event.schema_id)
return fastavro.schemaless_reader(io.BytesIO(producer_event.payload), schema)Caching is safe because a schema ID identifies one immutable schema. The ID never refers to different content later.
Use the ID on each event
Do not assume the ID from GetTopic fits every event. Each event carries its own schema_id. When an admin adds a field to a platform event or custom object, new events use a new ID, while events still in the retention window keep the old one. decode_event above reads the ID from the event itself, so it handles both. Fetch the schema when you see an ID for the first time, not once at startup.
Common errors
- Missing or wrong metadata. An
UNAUTHENTICATEDstatus usually means an expired token or aninstanceurlortenantidthat doesn't match the token's org. - Wrong topic name. Platform events use the
/event/prefix and change events use/data/. A misspelled name returns an error fromGetTopic. - Decoding with a stale schema. Using the topic's current schema on an older event can give garbage values or exceptions. Always decode with the event's own
schema_id. - Treating
GetSchemaas per-event. Calling it for every event adds a network round trip each time. Cache it.
Exercise
A subscriber decodes every event with the schema it fetched at startup. An admin adds a field to the event, and the subscriber later starts failing on some events. What is the fix?
Show answer
Read schema_id from each event and call get_schema with that ID. Cache the parsed schema by ID, so each ID costs one GetSchema call. Events published before the change keep their old ID, and newer events use the new one.