Before you begin, make sure you have installed
protoc and the runtime library for your language. See the Installation guide for instructions.Define a .proto file
Create a file named A few things to note:
addressbook.proto. This schema defines two messages: Person (with nested PhoneNumber and PhoneType) and AddressBook.addressbook.proto
syntax = "proto3"selects the proto3 language version.- Field numbers (e.g.,
= 1,= 2) uniquely identify each field in the binary encoding. They must not change once your message type is in use. - The
repeatedkeyword means the field can appear zero or more times (equivalent to a list). import "google/protobuf/timestamp.proto"pulls in a well-known type bundled with protobuf.
Compile with protoc
Run This generates
protoc against your .proto file and specify the output directory for your target language.- Python
- Java
- C++
- C#
- Ruby
- PHP
addressbook_pb2.py in the current directory.To also generate a .pyi type stub for IDE support:Write data
Use the generated classes to build and serialize a message. The following examples read an address book from a file, add a person, and write it back out.
- Python
- Java
- C++
add_person.py
Cross-language compatibility
Because all language runtimes share the same binary wire format, you can write data with one language and read it with another. For example, the address book examples in the protobuf repository all use the sameaddressbook.data file:
Next steps
- Read the Installation guide to set up
protocand your language runtime. - Explore the full set of scalar types, nested messages, and field options in the proto3 language reference.