gRPC Guide

Proto3 Definition

syntax = "proto3"; package users.v1; option go_package = "gen/users/v1"; // Message definition message User { uint32 id = 1; string name = 2; string email = 3; bool active = 4; repeated string roles = 5; } message GetUserRequest { uint32 id = 1; } message ListUsersRequest { uint32 page = 1; uint32 limit = 2; string filter = 3; } message ListUsersResponse { repeated User users = 1; } // Service definition service UserService { rpc GetUser(GetUserRequest) returns (User); rpc ListUsers(ListUsersRequest) returns (ListUsersResponse); rpc CreateUser(User) returns (User); // Server streaming rpc WatchUsers(ListUsersRequest) returns (stream User); // Client streaming rpc BulkCreate(stream User) returns (ListUsersResponse); // Bidirectional streaming rpc Chat(stream Message) returns (stream Message); }

Code Generation

# Install protoc brew install protobuf # macOS apt install protobuf-compiler # Ubuntu # Go go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest protoc --go_out=. --go-grpc_out=. proto/users.proto # Node.js npm install @grpc/grpc-js @grpc/proto-loader # Or use grpc-tools npx grpc_tools_node_protoc --js_out=. --grpc_out=. proto/users.proto

gRPC vs REST

FeaturegRPCREST
ProtocolHTTP/2HTTP/1.1+
SerializationProtobuf (binary)JSON (text)
Streaming✓ Built-inLimited (SSE)
Type safety✓ Schema enforcedOptional
Browser supportNeeds proxy✓ Native