protoruf — LLM Usage Prompt (Python)¶
Feed this file to an LLM (or paste it into a system prompt) so it can use the Python target of
protorufcorrectly with no other context. It is a complete, self-contained reference for version 0.4.0.
What protoruf is¶
protoruf converts between JSON and Protobuf dynamically — no protoc, no
generated classes. You compile a .proto to a descriptor set once, then
convert JSON ↔ Protobuf wire bytes in both directions. The engine is pure Rust
(exposed to Python via PyO3), so conversions run at Rust speed.
Core idea: descriptor (compiled schema, bytes) + message_type (fully
qualified name like "user.User") are required for every conversion.
Install¶
Requires Python ≥ 3.12. Pydantic (≥ 2) is a required runtime dependency — it is imported at package load and powers the Pydantic helper functions.
The mental model (3 steps)¶
- Compile a
.protoschema to a descriptor (bytes) — do this once. - Convert
json_to_protobuf/protobuf_to_jsonusing that descriptor and amessage_type. - For throughput, wrap the descriptor in a
DescriptorCacheand reuse it.
Complete public API¶
All names below are importable from the top-level protoruf package:
from protoruf import (
compile_proto,
compile_proto_from_sources,
compile_protos,
load_descriptor,
json_to_protobuf,
protobuf_to_json,
pydantic_to_protobuf,
protobuf_to_pydantic,
DescriptorCache,
Schema,
Codec,
)
Compilation¶
def compile_proto(
proto_path: str | Path,
include_paths: list[str | Path] | None = None,
output_path: str | Path | None = None,
) -> bytes
.proto file from disk. include_paths defaults to the parent
directory of proto_path. If output_path is given, the descriptor is also
written there (as a .desc file). Raises RuntimeError on compile failure.
def compile_proto_from_sources(
files: dict[str, str],
root: str,
include_imports: bool = True,
output_path: str | Path | None = None,
) -> bytes
.proto sources held in memory (no filesystem). files maps a
logical filename → its source text; import statements resolve by name within
this map. Google well-known types are provided automatically. root is the entry
file (must be a key of files). include_imports=True embeds imported files so
the descriptor is self-contained; False produces a smaller, faster-decoding
descriptor when you don't need well-known types.
def compile_protos(
roots: Sequence[str | Path],
include_paths: Sequence[str | Path] = (),
sources: Mapping[str, str] | None = None,
*,
include_imports: bool = True,
source_info: bool = False,
standard_protos: bool = True,
output_path: str | Path | None = None,
) -> bytes
sources first, then include_paths, then the embedded standard protos
(google/rpc/*, google/type/*, grpc/health/v1, grpc/reflection/{v1,v1alpha},
unless standard_protos=False), then google/protobuf/*. A root is an import name or
a path inside an include path. source_info=True keeps comments (needed by
Schema to expose them). Raises RuntimeError whose message starts with
file.proto:line:column:.
Read a pre-compiled .desc file back into bytes. Raises FileNotFoundError if
missing.
Conversion (one-shot)¶
def json_to_protobuf(json_str: str, descriptor_bytes: bytes, message_type: str) -> bytes
def protobuf_to_json(protobuf_bytes: bytes, descriptor_bytes: bytes, message_type: str, pretty: bool = False, include_default_values: bool = False) -> str
message_type is the fully qualified name: "<package>.<Message>", e.g.
"user.User". pretty=True indents the JSON output. include_default_values=True
emits fields without presence even at their default value (fields with presence —
optional, messages — still only when set). These re-resolve the message
type on every call; for hot loops use DescriptorCache.
Pydantic helpers (free functions)¶
def pydantic_to_protobuf(pydantic_model: BaseModel, descriptor_bytes: bytes, message_type: str) -> bytes
def protobuf_to_pydantic(protobuf_bytes: bytes, descriptor_bytes: bytes, model_class: Type[T], message_type: str) -> T
pydantic_to_protobuf calls model.model_dump_json() then
json_to_protobuf; protobuf_to_pydantic calls protobuf_to_json(...,
include_default_values=True) then model_class.model_validate_json(). Models with
bytes fields go through Python objects so that bytes are carried as base64; no
model configuration is needed. Note the argument order:
protobuf_to_pydantic(bytes, descriptor, ModelClass, message_type).
DescriptorCache (high-throughput)¶
Free functions reuse decoded pools through a process-wide LRU, but hash the
descriptor bytes and resolve the message type on every call. DescriptorCache
holds the pool and memoizes message descriptors, avoiding that per-call work.
One instance handles every message type and is safe to share across threads.
class DescriptorCache:
def __init__(self, descriptor_bytes: bytes) -> None: ...
def json_to_protobuf(self, json_str: str, message_type: str) -> bytes: ...
def protobuf_to_json(self, protobuf_bytes: bytes, message_type: str, pretty: bool = False, include_default_values: bool = False) -> str: ...
def pydantic_to_protobuf(self, pydantic_model: BaseModel, message_type: str) -> bytes: ...
def protobuf_to_pydantic(self, protobuf_bytes: bytes, model_class: Type[T], message_type: str) -> T: ...
descriptor_bytes argument (the pool is already
decoded). Output format is identical to the free functions.
Schema (introspection)¶
class Schema:
def __init__(self, descriptor: bytes) -> None: ...
files: Mapping[str, FileInfo]; messages: Mapping[str, MessageInfo]
enums: Mapping[str, EnumInfo]; services: Mapping[str, ServiceInfo]
def message(self, full_name: str) -> MessageInfo: ... # also file(), enum(), service()
def file_descriptor_proto(self, name: str) -> bytes: ...
def file_containing_symbol(self, symbol: str) -> str | None: ...
def file_dependencies(self, name: str) -> tuple[str, ...]: ...
MessageInfo.fields (declaration order),
FieldInfo.kind ("int32", …, "enum", "message"), type_name, cardinality,
is_map, has_presence, oneof (real oneofs only), comments.text, etc. Messages
include nested ones and map entries (is_map_entry=True). Comments need
source_info=True at compile time; unknown names raise KeyError.
Codec (protobuf ↔ Python objects, no JSON — the fastest path)¶
codec = Schema(descriptor).codec(
"pkg.Message", Model, # Model: Pydantic class, or None for dicts
mode="validate", # or "construct" (no validation), "dict"
field_names={"pkg.Message": {3: "from_"}}, # only when a Python name differs
)
data: bytes = codec.encode(instance_or_dict)
instance = codec.decode(data)
None = absent for
optional, messages and oneof members). Timestamp ↔ aware datetime, Duration ↔
timedelta, google.type.Date ↔ date, Struct ↔ dict, wrappers ↔ scalar or None.
Two members of a oneof set at once → ValueError. Bytes identical to google.protobuf.
Canonical examples¶
Minimal round-trip (from disk)¶
from protoruf import compile_proto, json_to_protobuf, protobuf_to_json
descriptor = compile_proto("message.proto")
pb = json_to_protobuf('{"id": "123"}', descriptor, message_type="message.Message")
print(protobuf_to_json(pb, descriptor, message_type="message.Message", pretty=True))
Compile from in-memory sources¶
from protoruf import compile_proto_from_sources, json_to_protobuf
files = {
"user.proto": '''
syntax = "proto3";
package user;
message User { string id = 1; string email = 2; }
''',
}
descriptor = compile_proto_from_sources(files, root="user.proto")
pb = json_to_protobuf('{"id":"1","email":"a@b.com"}', descriptor, "user.User")
High-throughput loop with DescriptorCache¶
from protoruf import compile_proto, DescriptorCache
cache = DescriptorCache(compile_proto("schema.proto")) # decode pool once
for json_data in json_stream:
pb = cache.json_to_protobuf(json_data, "message.Message")
process(pb)
restored = cache.protobuf_to_json(pb, "message.Message", pretty=True)
Pydantic integration¶
from pydantic import BaseModel
from protoruf import compile_proto, DescriptorCache
class Message(BaseModel):
id: str = ""
content: str = ""
cache = DescriptorCache(compile_proto("schema.proto"))
pb = cache.pydantic_to_protobuf(Message(id="123", content="hi"), "message.Message")
msg = cache.protobuf_to_pydantic(pb, Message, "message.Message")
JSON shape — READ THIS (non-standard)¶
protoruf uses a specific, non-default JSON mapping. When generating or validating JSON for it, follow these rules exactly:
- Field names are proto names (
snake_case), NOT the camelCase of canonical protobuf JSON. Usecreated_at, notcreatedAt. - Enums are emitted as numbers (their integer value), not names. On input, numbers are expected; enum names may also be accepted on input but output is always numeric.
- 64-bit integers (
int64/uint64/sint64/fixed64) are JSON numbers, not strings. ⚠️ Precision caveat: values above 2^53 lose precision in a standard JSON reader. Consumers needing exact large 64-bit values must use a big-integer-aware JSON parser. bytesfields map to standard base64-encoded strings.- Fields at their proto3 default (0,
"",false, empty repeated/map) are omitted from the output JSON by default. Don't rely on them being present after a round-trip, or passinclude_default_values=Trueto emit them (the Pydantic helpers do this, so required fields holding a zero value validate). - Standard proto3 JSON applies otherwise (nested messages → objects, repeated →
arrays, map → object,
oneof→ the single set field, well-known types likeTimestamp/Duration/Structuse their canonical JSON forms).
Errors¶
| Exception | When |
|---|---|
RuntimeError |
proto compilation fails; any failure in protobuf_to_json including an unknown message_type in that direction; protobuf decode/serialize failure |
ValueError |
invalid JSON input, or message_type not found — in the json_to_protobuf direction; also raised by DescriptorCache(...) if the descriptor bytes can't be decoded |
FileNotFoundError |
load_descriptor path does not exist |
pydantic.ValidationError |
decoded JSON doesn't match the target Pydantic model |
Note the asymmetry: a wrong
message_typeraisesValueErrorinjson_to_protobufbutRuntimeErrorinprotobuf_to_json.
Rules for the LLM¶
- Always compile (or load) a descriptor before converting; every conversion
needs both
descriptor_bytesand a fully-qualifiedmessage_type. message_typemust be"<package>.<Message>"matching the.proto'spackageand message name — a wrong name raisesValueErrorinjson_to_protobufandRuntimeErrorinprotobuf_to_json.- In the browser there is no filesystem — but this is the Python target, so
compile_proto(path)is available and fine here. - For more than a few conversions, build one
DescriptorCacheand reuse it; don't call the free functions in a tight loop. To go between protobuf bytes and Pydantic models, preferSchema(descriptor).codec(...): no JSON step at all. - Emit JSON in protoruf's shape (snake_case fields, numeric enums, numeric 64-bit ints) — do not assume canonical camelCase protobuf JSON.