The shape of a .proto file
A .proto file is a blueprint for a message. The compiler turns it into code for each language, and the data on the wire carries field numbers rather than field names. That is why the numbering rules matter more than the grammar.
Top-level declarations
| Declaration | Role | When absent |
|---|---|---|
syntax | Chooses proto2 or proto3; omitted means proto2 | Treated as proto2 with a note |
package | Prefix for message names, prevents collisions | Names stand alone |
import | Messages defined in another file | External types do not resolve |
message | A group of fields, may nest | — |
enum | A named set of integer constants | — |
service | A group of gRPC methods | — |
One field line
In optional string city = 2; the order is label, type, name and number. proto3 omits labels except repeated. required is banned in proto3, and an explicit optional means explicit presence from 3.15 onward.
- Field numbers run from 1 to 536,870,911.
- 19000 to 19999 is reserved by the Protobuf implementation and cannot be used.
- 1 to 15 encode their tag in one byte, which suits fields you write often.
- Within one message, numbers and names must each be unique.
Enums start at zero
A proto3 enum must have a value numbered 0, and that value is the default. The linter raises an error when no zero value exists. Two names for one number need option allow_alias = true;.
oneof and map
A oneof groups fields so that only one is set; assigning another member clears the previous one. map<key, value> is encoded as a repeated entry message with the key at field 1 and the value at field 2, and the key type must be an integer, bool or string.
reserved marks deleted numbers
Leaving reserved 5; or reserved "legacy_ref"; behind after a deletion stops a future field from reusing the number or name. This tool reports a field that uses a reserved number or name as an error.
Start with syntax, package, one message and two or three fields. The linter lists what is missing in order, so filling the diagnostics away is the fastest way to a complete file.
Questions
Do I have to write syntax?
It is recommended. Omitting it means proto2, and the label and enum-zero rules change. This tool notes the omission and checks the file as proto2.
What happens if I change a field number?
The other side reads a different field, so values are lost or land in the wrong place. A number should be chosen once and kept.
When should a message be nested?
For a helper structure used only inside its parent. A structure you reuse belongs at the top level and is referenced by name.
The order-wire preset pairs a complete proto3 schema with bytes that match it.
Written against the Protobuf language guide (proto2 and proto3) and the Protobuf encoding documentation. Every schema, byte string and name here is synthetic.