Skip to content

About

A type adaptor which allows protobuf generated types to be used as pydantic models.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

8 Commits

Folders and files

Repository files navigation

protodantic

A type adaptor which allows protobuf generated types to be used as Pydantic models.

Installation

uv add git+https://github.com/Tehsmash/protodantic

Usage

Given a protobuf definition like this:

message Address {
  string street = 1;
  string city = 2;
  string country = 3;
}

message Person {
  string name = 1;
  int32 age = 2;
  Address address = 3;
  repeated string emails = 4;
  string display_name = 5;
}

Pass the generated class to model_from_proto to get a fully usable Pydantic model:

from protodantic import model_from_proto
from my_proto_pb2 import Person

PersonModel = model_from_proto(Person)

# Instantiate and validate
person = PersonModel(
    name="Alice",
    age=30,
    display_name="Alice Smith",
    emails=["[email protected]"],
)

# Serialise to dict — multi-word fields use camelCase keys by default
person.model_dump()
# {'name': 'Alice', 'age': 30, 'displayName': 'Alice Smith', 'address': None, 'emails': ['[email protected]']}

# Serialise to JSON
person.model_dump_json(exclude_none=True)
# '{"name":"Alice","age":30,"displayName":"Alice Smith","emails":["[email protected]"]}'

# Generate a JSON schema
PersonModel.model_json_schema()
# {'properties': {'name': ..., 'age': ..., 'address': ..., 'emails': ..., 'displayName': ...}, ...}

Nested messages are converted recursively — address above becomes its own Pydantic model with street, city, and country fields.

ProtoJSON compatibility

The generated models are designed to interoperate with the ProtoJSON encoding produced by google.protobuf.json_format.MessageToJson.

Loading from ProtoJSON

Feed MessageToJson output directly into model_validate_json:

from google.protobuf.json_format import MessageToJson
from my_proto_pb2 import Person

proto = Person(name="Alice", age=30, display_name="Alice Smith")
proto_json = MessageToJson(proto)
# '{\n  "name": "Alice",\n  "age": 30,\n  "displayName": "Alice Smith"\n}'

PersonModel = model_from_proto(Person)
person = PersonModel.model_validate_json(proto_json)
assert person.display_name == "Alice Smith"

Dumping ProtoJSON

model_dump_json(exclude_none=True) produces output that matches MessageToJson across all field types:

person = PersonModel(name="Alice", age=30, display_name="Alice Smith")
person.model_dump_json(exclude_none=True)
# '{"name":"Alice","age":30,"displayName":"Alice Smith"}'

camelCase field names

Multi-word field names are aliased to camelCase following the ProtoJSON spec (e.g. display_name ↔ displayName). Both names are accepted on input; camelCase is used by default on output.

# snake_case on input
person = PersonModel(display_name="Alice Smith")

# camelCase on input (e.g. from ProtoJSON)
person = PersonModel.model_validate({"displayName": "Alice Smith"})

assert person.display_name == "Alice Smith"
person.model_dump()  # {'displayName': 'Alice Smith', ...}

Enum fields

Enum fields use IntEnum. They accept both integer values and ProtoJSON string names on input. JSON output uses the string name to match the ProtoJSON spec; Python-mode output (model_dump()) returns the IntEnum member.

from my_proto_pb2 import Task, TASK_STATE_COMPLETED

TaskModel = model_from_proto(Task)

m = TaskModel(state=3)                    # integer value
m = TaskModel(state="TASK_STATE_COMPLETED")  # string name (ProtoJSON)

m.model_dump_json()   # '{"state":"TASK_STATE_COMPLETED"}'
m.model_dump()        # {'state': <TaskState.TASK_STATE_COMPLETED: 3>}

Bytes fields

bytes fields are base64-encoded on JSON output and base64-decoded on JSON input, matching the ProtoJSON spec:

m = PartModel(raw=b"hello world")
m.model_dump_json()   # '{"raw":"aGVsbG8gd29ybGQ="}'

# Round-trips correctly from MessageToJson output
m2 = PartModel.model_validate_json(m.model_dump_json())
assert m2.raw == b"hello world"

Timestamps

google.protobuf.Timestamp fields map to datetime.datetime. They are loaded from RFC 3339 strings (e.g. "2024-01-15T12:00:00Z") and serialized back to the same format:

import datetime
from google.protobuf.timestamp_pb2 import Timestamp
from my_proto_pb2 import TaskStatus

ts = Timestamp()
ts.FromDatetime(datetime.datetime(2024, 1, 15, 12, 0, 0, tzinfo=datetime.timezone.utc))
proto = TaskStatus(timestamp=ts)

TaskStatusModel = model_from_proto(TaskStatus)
m = TaskStatusModel.model_validate_json(MessageToJson(proto))
assert m.timestamp == datetime.datetime(2024, 1, 15, 12, 0, 0, tzinfo=datetime.timezone.utc)

oneof fields

Real oneof groups (with two or more fields) are enforced — setting more than one field in the group raises a ValidationError. Proto3 synthetic single-field oneofs (used to implement optional) are not enforced.

PartModel = model_from_proto(Part)
PartModel(text="hello")                              # ok
PartModel(text="hello", url="http://example.com")    # raises ValidationError

Field type mapping

Protobuf Python
string str
bool bool
int32, int64, uint32, uint64, … int
float, double float
bytes bytes (base64 in JSON)
enum IntEnum (string name in JSON)
message Foo Pydantic model (recursively converted)
repeated T List[T]
map<K, V> Dict[K, V]
google.protobuf.Struct Dict[str, Any]
google.protobuf.Timestamp datetime.datetime (RFC 3339 in JSON)
google.protobuf.Duration datetime.timedelta
google.protobuf.Value Any
google.protobuf.ListValue List[Any]
google.protobuf.Any Any

All fields are Optional with a default of None, matching proto3 semantics.

About

A type adaptor which allows protobuf generated types to be used as pydantic models.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages