Protocol Buffers Tutorial: Writing a .proto File
On this page
The .proto contract comes first
In gRPC, the .proto file is the API. Code in every language is generated from it, so it's worth writing carefully and reviewing like any other public interface.
Example .proto file: an order service
This file defines the order service used throughout the course. It passes buf lint with the STANDARD rules:
syntax = "proto3";
package shop.v1;
option go_package = "grpclab/gen/shop/v1;shopv1";
import "google/protobuf/timestamp.proto";
// OrderService manages customer orders.
service OrderService {
// Unary: one request, one response.
rpc GetOrder(GetOrderRequest) returns (GetOrderResponse);
// Unary, idempotent with a client-supplied key.
rpc CreateOrder(CreateOrderRequest) returns (CreateOrderResponse);
// Server streaming: status updates until the order is delivered.
rpc WatchOrder(WatchOrderRequest) returns (stream WatchOrderResponse);
// Client streaming: many line items in, one summary out.
rpc UploadItems(stream UploadItemsRequest) returns (UploadItemsResponse);
// Bidirectional streaming: chat with support about an order.
rpc SupportChat(stream SupportChatRequest) returns (stream SupportChatResponse);
}
message Order {
enum Status {
STATUS_UNSPECIFIED = 0;
STATUS_PENDING = 1;
STATUS_PAID = 2;
STATUS_SHIPPED = 3;
STATUS_DELIVERED = 4;
}
string id = 1;
string customer_id = 2;
Status status = 3;
int64 total_cents = 4;
repeated LineItem items = 5;
google.protobuf.Timestamp created_at = 6;
message LineItem {
string sku = 1;
int32 quantity = 2;
int64 unit_price_cents = 3;
}
}
message GetOrderRequest { string order_id = 1; }
message GetOrderResponse { Order order = 1; }(The remaining request and response messages follow the same pattern.)
Reading a .proto file line by line
syntax = "proto3": the current language version. (Protobuf "editions", starting with edition 2023, are gradually replacing the syntax line with finer-grained feature settings; proto3 remains fully supported.)package shop.v1: a namespace that prevents name clashes, with the major version in it (Day 23).option go_package: where Go code is generated. Other languages have their own options (java_package,csharp_namespace).import: reuse other definitions, here Google's standardTimestamp(Day 21).servicewithrpcmethods: the operations.streammarks streaming directions.message: a structured type. Each field has a type, a name and a unique field number (= 1). Numbers, not names, identify fields on the wire, so they must never be reused (Day 13).repeated: a list.- Nested types (
Order.Status,Order.LineItem) keep related definitions together.
Protobuf style conventions worth following
buf lint enforces most of these:
- One request and one response message per RPC, named
<Method>Requestand<Method>Response, even if one would do: you can add fields later without changing the method signature. - Field names in
lower_snake_case; generated code converts them (customer_idbecomesCustomerIdin Go,customerIdin JSON). - Enum values prefixed with the enum name (
STATUS_PAID) and a zero value named..._UNSPECIFIED, because 0 is the default and shouldn't mean anything real. - Packages versioned (
shop.v1) and files in matching directories (proto/shop/v1/orders.proto). - Comments on services, methods and fields: they flow into generated code and documentation.
Lint failures from an early draft of the course's examples show the kind of thing it catches:
event.proto:2:1: Files with package "demo" must be within a directory "demo" relative to root but were in directory ".".
event.proto:2:1: Package name "demo" should be suffixed with a correctly formed version, such as "demo.v1".Check yourself
Fields can be added to one RPC's request or response later without changing the method's signature or affecting other RPCs that would otherwise share the message. It's the main way gRPC APIs evolve safely.
Zero is the default when a field isn't set, so it shouldn't stand for a real state that could be confused with "missing".
Its number. Names exist only in the schema and generated code, while the binary encoding carries the field number. That's why field numbers must stay stable and never be reused for something else.
It namespaces messages and services, so names don't collide across teams, and it becomes part of the fully qualified method name, like shop.orders.v1.OrderService/GetOrder.
PascalCase for messages, services and RPCs, snake_case for fields, and UPPER_SNAKE_CASE for enum values prefixed with the enum name, like ORDER_STATUS_PAID. Generators convert names into each language's style, and buf lint enforces the conventions.