Sub topic 4
Generating client stubs from pubsub_api.proto
This chapter assumes you can read Python, know what a gRPC streaming call is from the previous chapter, and have a Python 3 environment where you can install packages with pip. You do not need a Salesforce org yet. Nothing here makes a network call.
Why you need generated code
The Pub/Sub API is described by one Protocol Buffers file, pubsub_api.proto. Salesforce publishes it in the pub-sub-api repository on GitHub. The file defines every RPC, every message type, and every enum the service uses. The GetTopic, GetSchema, and Subscribe calls in later chapters are all declared in it.
Python cannot call a gRPC service directly from a .proto file. You run a compiler over the file and it writes Python modules. Your code imports those modules and uses them.
A stub is the client-side object that exposes each RPC as a method. When you call stub.GetTopic(...), the stub serializes your request, sends it over the channel, and parses the reply.
What the compiler produces
The compiler writes two Python files for each .proto file.
| Generated file | Contents | Used for |
|---|---|---|
| `pubsub_api_pb2.py` | Message classes and enums, such as `TopicRequest`, `FetchRequest`, and `ReplayPreset` | Building requests and reading responses |
| `pubsub_api_pb2_grpc.py` | The `PubSubStub` client class and the `PubSubServicer` server base class | Calling RPCs on a channel |
The suffix _pb2 is historical. It marks the second major version of the Protocol Buffers Python API and is still used today. The earlier code examples already use both modules: pb2.TopicRequest comes from the first file and pb2_grpc.PubSubStub comes from the second.
Message classes are plain data holders. You build one with keyword arguments, and any field you leave out takes its default value. That is 0 for numbers, "" for strings, empty bytes for bytes, and the first enum value for enums.
Setting up the environment
Use a virtual environment so the pinned versions do not collide with other projects. Install the runtime library, the compiler plugin, and the Avro decoder used in later chapters.
python3 -m venv .venv
source .venv/bin/activate
pip install grpcio grpcio-tools fastavrogrpcio is the runtime that opens channels and streams. grpcio-tools bundles protoc, the Protocol Buffers compiler, together with the Python gRPC plugin. You do not have to install protoc separately. fastavro is the Avro decoder used in the decoding chapter.
Getting the proto file
Download pubsub_api.proto from the Salesforce pub-sub-api repository, and keep it in a directory of your own, for example proto/. Keep a copy of the exact file you compiled against in version control. The service can gain new fields and RPCs over time, and a stored copy lets you tell which version your generated code matches.
mkdir -p proto
curl -L -o proto/pubsub_api.proto \
https://raw.githubusercontent.com/forcedotcom/pub-sub-api/main/pubsub_api.protoRunning the compiler
Run grpc_tools.protoc as a Python module. The -I flag sets the import root, --python_out sets where the message module goes, and --grpc_python_out sets where the stub module goes.
python -m grpc_tools.protoc \
-I proto \
--python_out=. \
--grpc_python_out=. \
proto/pubsub_api.protoAfter this command, the current directory holds pubsub_api_pb2.py and pubsub_api_pb2_grpc.py. Check that both exist with ls.
The generated stub module imports the message module with a plain import pubsub_api_pb2. This works only if both files are in the same directory and that directory is on sys.path. Running your script from the directory that holds the generated files satisfies that. Keep this in mind if you move the files into a package, which is covered below.
How the compiler flow fits together
The diagram shows what goes in and what comes out, and which modules your code touches.
Checking that the generated code works
A quick smoke test confirms the files import and that the names you will rely on exist. This test needs no credentials and no network.
import pubsub_api_pb2 as pb2
import pubsub_api_pb2_grpc as pb2_grpc
request = pb2.TopicRequest(topic_name="/data/AccountChangeEvent")
print(request.topic_name)
fetch = pb2.FetchRequest(
topic_name="/data/AccountChangeEvent",
replay_preset=pb2.ReplayPreset.LATEST,
num_requested=5,
)
print(fetch.num_requested, fetch.replay_preset)
print(hasattr(pb2_grpc, "PubSubStub"))The script prints the topic name, then 5 followed by the numeric value of LATEST, then True. If the last line prints False, the stub module was generated from the wrong file or the compile step failed silently.
Note how enums behave. pb2.ReplayPreset.LATEST is an integer constant, not a string. If you print a field that holds an enum, you see a number. To get the name back, use pb2.ReplayPreset.Name(value).
import pubsub_api_pb2 as pb2
value = pb2.ReplayPreset.LATEST
print(value, pb2.ReplayPreset.Name(value))Reading the proto file
You do not need to memorize pubsub_api.proto, but you should know how to read it. Open it and look for these parts.
- The
service PubSubblock lists the RPCs. Each line names a method, its request type, and its reply type. - A
streamkeyword before a type marks a streaming direction.Subscribehasstreamon both sides, which makes it bidirectional. messageblocks define the structures. Each field has a type, a name, and a field number.enumblocks define fixed value sets such asReplayPreset.
The field numbers are what travel on the wire, not the names. This is why the server and your client can differ slightly in version and still communicate. A field the client does not know about is ignored. A field the server does not receive takes its default.
A field with a default value can hide a mistake. If you misspell a keyword argument, Python raises an error. If you forget a required piece of data, the library does not complain. It sends the default, and the server decides whether that is acceptable. For example, a FetchRequest without num_requested sends 0, and no events flow after the first batch request.
Common errors
The table lists the failures learners meet most often at this step.
| Symptom | Likely cause | Fix |
|---|---|---|
| `ModuleNotFoundError: No module named 'grpc_tools'` | `grpcio-tools` is not installed in the active environment | Activate the virtual environment and run `pip install grpcio-tools` |
| `ModuleNotFoundError: No module named 'pubsub_api_pb2'` | The generated files are not in the script's directory or on `sys.path` | Run from the output directory, or fix the import path |
| `protoc` reports `File does not reside within any path` | The proto path given does not sit under an `-I` directory | Make the `-I` directory a parent of the file path |
| `TypeError: Descriptors cannot be created directly` | The `protobuf` runtime is older or newer than the one that generated the code | Regenerate the code with the installed `grpcio-tools`, or align the `protobuf` version |
| `AttributeError: module has no attribute 'PubSubStub'` | You imported `pubsub_api_pb2` where you needed `pubsub_api_pb2_grpc` | Import the `_grpc` module for the stub |
Placing generated code in a package
In a real project you will not want generated files mixed with your own code. Two common layouts work.
The first layout keeps the generated files at the project root next to the entry script. It is the simplest and matches the examples in this tutorial.
The second puts them in a package such as generated/. The stub module's bare import pubsub_api_pb2 then fails, because Python looks for a top-level module of that name. You have two options. You can add the generated/ directory to sys.path before importing. Or you can compile with the package-relative layout, passing the proto file inside a directory that matches the package name, so the compiler writes from generated import pubsub_api_pb2.
mkdir -p src/generated
touch src/generated/__init__.py
cp proto/pubsub_api.proto src/generated/pubsub_api.proto
python -m grpc_tools.protoc \
-I src \
--python_out=src \
--grpc_python_out=src \
src/generated/pubsub_api.protoThe import path in the proto argument decides the import line in the generated stub. Because the proto file is generated/pubsub_api.proto relative to -I src, the compiler writes from generated import pubsub_api_pb2. Then your code imports from generated import pubsub_api_pb2_grpc.
Keeping the stubs current
Salesforce can add fields, RPCs, and enum values to the proto file. Old generated code keeps working, because unknown fields are ignored and old fields keep their numbers. You will not see new features until you fetch the new proto and compile again.
Update on purpose, not by accident. Fetch the new file, diff it against your stored copy, regenerate, and run your tests. Reading the diff tells you whether a change affects you. A new RPC you do not call is harmless. A change to a message you build or parse deserves a look.
What comes next
With the stubs generated, you can create a PubSubStub from a channel and call RPCs. The next chapter covers how to authenticate and which metadata headers each call needs. The describe_topic function you saw earlier already depends on the generated TopicRequest and PubSubStub classes.
Exercise
You compile pubsub_api.proto and then run a script that does import pubsub_api_pb2_grpc as pb2_grpc and pb2_grpc.TopicRequest(topic_name="/data/AccountChangeEvent"). It fails with AttributeError. What is wrong, and how do you fix it?
Show answer
TopicRequest is a message class, so it lives in pubsub_api_pb2, not in pubsub_api_pb2_grpc. The _grpc module holds only the stub and servicer classes. Import pubsub_api_pb2 as pb2 and call pb2.TopicRequest(topic_name="/data/AccountChangeEvent").
Exercise
You move the generated files into a generated/ package and now import pubsub_api_pb2 inside pubsub_api_pb2_grpc.py fails. Give two ways to resolve it.
Show answer
First, add the generated/ directory to sys.path before the import so the bare module name resolves. Second, recompile with -I pointing at the parent directory and give the proto path as generated/pubsub_api.proto, so the compiler writes from generated import pubsub_api_pb2 into the stub. The second option is cleaner because it needs no path changes at runtime.
Exercise
A teammate generates code on a laptop and deploys it to a server where the protobuf package is a different version. The import now raises TypeError: Descriptors cannot be created directly. What is the durable fix?
Show answer
Pin grpcio, grpcio-tools, and protobuf to the same versions in the requirements file for every environment, then regenerate the stubs with those versions. Compiling and running with matching versions avoids the descriptor mismatch.