Defining Your First Protocol Buffer

To define the language independent data structures that your software will use, you start by defining one or more message types, stored in one or more .proto files.

The following example is a User type, with two simple properties. You'll notice that the age field is typed as int32, which you may be unfamiliar with depending on which languages you use. If you're coming from something like JavaScript with a single Number type, just know that int32, int64, float32, and float64 are more specific number types that will be translated for you.

message User {
  string name = 1;
  int32 age = 2;
}

You can also refer to other message types and define lists.

message UserList {
  repeated User users = 1;
}

For complete documentation of the syntax see Language Guide – Protocol Buffers, and for common definitions like timestamps and durations you can use in your own projects see Well Known Types.

From .proto files to code

The next step is to compile your .proto files with protoc, which will create stub code for working with the types defined. protoc can generate code for several languages, but we'll look at the code for reading and writing the above definitions in a few of the more popular languages.

  • Document the protoc command from old sample project
  • Flesh out code samples using https://developers.google.com/protocol-buffers/docs/tutorials as base

JavaScript

Python

Go

C++?