Loading Protobuf to Python Converter...
Please wait a moment

How to Turn a .proto File into Python Dataclasses

When a service speaks Protocol Buffers but your Python code only ever sees the JSON version of its messages, the full protobuf runtime is more than you need. This page reads the .proto file and writes typed dataclasses for its messages, with methods that read and write the same JSON protobuf produces.

Step 1

Paste or upload the .proto file

Paste a schema into the left editor, upload a .proto file (up to 10 MB), or press Sample. proto2, proto3 and edition files are read, and a snippet without a syntax line is treated as proto3. The page needs the schema itself; Protobuf data (text format or binary) is pointed to Protobuf to JSON instead.

Example: a small order schema

syntax = "proto3";

package shop.v1;

message Order {
  int64 id = 1;
  string customer_id = 2;
  repeated string tags = 3;
  optional string coupon = 4;
}
Step 2

Look over the Python classes

Each message becomes a dataclass with type hints, a from_dict() classmethod and a to_dict() method, and each enum becomes an IntEnum. Notes above the code tell you about anything that needs a second look, such as a service that was left out or a type from a file you did not paste. A mistake in the .proto file shows up as an error with its line and column.

What the page writes for that schema

The id is a plain int that to_dict() writes as a string, the optional coupon starts as None, and the helper functions at the bottom are only the ones these classes use.

# Python dataclasses for the messages in this .proto file. from_dict() reads the JSON
# protobuf writes (json_format.MessageToDict, protojson, grpc-gateway) and to_dict() writes it
# back. Only the standard library is used. For the binary wire format and gRPC stubs,
# generate code with: python -m grpc_tools.protoc --python_out=. your.proto
#
#   obj = Order.from_dict(json.loads(text))
#   text = json.dumps(obj.to_dict())
#
# Note: 64-bit integers are plain Python ints, so long IDs such as 8901240544102066246 keep every digit. to_dict() writes them as strings, the way protobuf's JSON does, and from_dict() accepts either a number or a string.

from __future__ import annotations

from dataclasses import dataclass, field as _field
from typing import Any, Dict, List, Optional


@dataclass
class Order:
    """The message shop.v1.Order."""

    id: int = 0
    customer_id: str = ""
    tags: List[str] = _field(default_factory=list)
    coupon: Optional[str] = None

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> Order:
        obj = cls()
        v = _get(data, "id")
        if v is not None:
            obj.id = _int(v)
        v = _get(data, "customerId", "customer_id")
        if v is not None:
            obj.customer_id = _str(v)
        v = _get(data, "tags")
        if v is not None:
            obj.tags = [_str(x) for x in _list(v)]
        v = _get(data, "coupon")
        if v is not None:
            obj.coupon = _str(v)
        return obj

    def to_dict(self) -> Dict[str, Any]:
        out: Dict[str, Any] = {}
        if self.id:
            out["id"] = str(self.id)
        if self.customer_id:
            out["customerId"] = self.customer_id
        if self.tags:
            out["tags"] = [x for x in self.tags]
        if self.coupon is not None:
            out["coupon"] = self.coupon
        return out


def _get(data: Dict[str, Any], *names: str) -> Any:
    # protobuf's JSON parser accepts the JSON name and the original field name; null means not set
    for name in names:
        if name in data:
            return data[name]
    return None


def _list(v: Any) -> List[Any]:
    if not isinstance(v, list):
        raise ValueError(f"expected a list, got {v!r}")
    return v


def _int(v: Any) -> int:
    # 64-bit numbers arrive as strings in protobuf's JSON, so strings are accepted too
    if isinstance(v, bool):
        raise ValueError(f"expected an integer, got {v!r}")
    if isinstance(v, int):
        return v
    if isinstance(v, float) and v.is_integer():
        return int(v)
    if isinstance(v, str):
        return int(v)
    raise ValueError(f"expected an integer, got {v!r}")


def _str(v: Any) -> str:
    if not isinstance(v, str):
        raise ValueError(f"expected a string, got {v!r}")
    return v
Step 3

Copy or download protobuf_models.py

Copy the code or download protobuf_models.py into your project. It uses only the Python standard library and needs Python 3.7 or newer.

import json
from protobuf_models import Order

order = Order.from_dict(json.loads('{"id": "8901240544102066246", "customerId": "c-7"}'))
print(order.id + 1)                # 8901240544102066247
print(json.dumps(order.to_dict()))  # {"id": "8901240544102066246", "customerId": "c-7"}

Need the binary format or gRPC stubs as well? Run grpc_tools.protoc on the same file. To check a schema before converting it, use the Proto File Validator, and if all you have is a JSON sample, JSON to Python builds classes from the data itself.

Frequently Asked Questions

How is this different from what protoc generates for Python?

protoc --python_out writes message classes backed by the protobuf runtime, which you need for the binary wire format and for gRPC. This page writes plain dataclasses instead: no protobuf package, just type hints your editor and mypy understand, plus from_dict() and to_dict() for the JSON form of a message. That suits REST clients, test fixtures and scripts that only ever see JSON. Field names stay as they are in the .proto file, so user_id is user_id in Python and userId in JSON.

Which JSON does from_dict() read and to_dict() write?

The JSON mapping protobuf itself uses, the same thing json_format.MessageToDict, protojson in Go or grpc-gateway produce. from_dict() accepts the camelCase JSON name or the original field name, 64-bit numbers as strings or numbers, enum values by name or number, and bytes as Base64. to_dict() writes it back the way protobuf does: fields left at their default are skipped, 64-bit integers are strings and enums are names. We checked this against Google's own protobuf package, which reads the result back as the same message.

Do long int64 IDs keep every digit?

Yes. Python integers have no size limit, so an int64 or uint64 field holds 8901240544102066246 or 18446744073709551615 exactly, whether it arrived as a JSON number or as a quoted string. The page never turns a 64-bit field into str: it is typed int. Only to_dict() puts it in quotes, because that is how protobuf writes 64-bit numbers in JSON.

How are .proto types mapped to Python?

All integer types become int, float and double become float, bool, string and bytes map straight across, repeated fields become List[...] and map<K, V> fields become Dict[K, V]. Other messages are Optional[...] and start as None. Fields marked optional, oneof members and every single field in proto2 also start as None, so you can tell an unset field from one set to 0 or an empty string. google.protobuf.Timestamp and Duration stay as the text protobuf writes, Struct becomes a dict and the wrapper types become Optional values.

What happens to names Python does not allow, services and imports?

A field or enum value named after a Python keyword gets an underscore, so class becomes class_ and None becomes None_, while the JSON still uses the original name. Nested messages become top-level classes such as Order_LineItem. Services are left out with a note, since gRPC stubs come from grpc_tools.protoc. A type from an imported file you did not paste is typed Any and passed through untouched. Default values and extensions are not carried over.

Is my .proto file uploaded anywhere?

No. The file is read and converted in your browser and is not sent to our server. Nothing is kept either: a reload starts with an empty editor.