Protobuf to Pydantic

0.3.3.1 · active · verified Thu Apr 16

protobuf-to-pydantic is a Python library that generates `pydantic.BaseModel` classes with parameter verification functions directly from Protobuf files (proto3 syntax). It supports both runtime object generation and plugin-based code generation, enabling robust data validation for Protobuf messages within Python applications. The library is actively maintained with frequent minor releases, currently at version 0.3.3.1.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to convert a Protobuf Message object into a Pydantic `BaseModel` at runtime using `msg_to_pydantic_model`. It includes a minimal simulated Protobuf message for immediate execution. For actual use, `UserMessage` would be imported from your generated `_pb2.py` files.

import sys
from typing import Type
from pydantic import BaseModel, Field
from google.protobuf.message import Message
from google.protobuf import descriptor_pool, descriptor_pb2
from protobuf_to_pydantic import msg_to_pydantic_model

# Simulate a generated protobuf message `demo_pb2.UserMessage`
# In a real scenario, this would come from `import demo_pb2`

pool = descriptor_pool.Default()
descriptor = descriptor_pb2.DescriptorProto()
descriptor.name = 'UserMessage'
descriptor.field.add(name='uid', number=1, type=descriptor_pb2.FieldDescriptorProto.TYPE_STRING)
descriptor.field.add(name='age', number=2, type=descriptor_pb2.FieldDescriptorProto.TYPE_INT32)
descriptor.field.add(name='user_name', number=3, type=descriptor_pb2.FieldDescriptorProto.TYPE_STRING)

pool.Add(descriptor)

# Create a mock Message class based on the descriptor
class UserMessage(Message):
    def __init__(self, uid='', age=0, user_name='', **kwargs):
        super().__init__(**kwargs)
        self.uid = uid
        self.age = age
        self.user_name = user_name
    DESCRIPTOR = pool.FindMessageTypeByName('UserMessage')

# Convert the Protobuf Message object to a Pydantic BaseModel
UserModel: Type[BaseModel] = msg_to_pydantic_model(UserMessage)

# Example usage of the generated Pydantic model
user_data = UserModel(uid='123', age=30, user_name='John Doe')
print(user_data.model_dump_json(indent=2))

# Access field info
# print({k: v.field_info for k, v in UserModel.__fields__.items()}) # For Pydantic v1
print({k: v.json_schema_extra for k, v in UserModel.model_fields.items()}) # For Pydantic v2+

view raw JSON →