gRPC Basics

gRPC protocol buffers and service definition.

Protocol Buffer Definition

Define service (.proto file)
syntax = "proto3";

package user;

// Message definition
message User {
  string id = 1;
  string name = 2;
  string email = 3;
}

message GetUserRequest {
  string id = 1;
}

// Service definition
service UserService {
  rpc GetUser(GetUserRequest) returns (User);
  rpc ListUsers(Empty) returns (stream User);
}

Data Types

Scalar types
string - text
int32, int64 - integers
float, double - decimals
bool - boolean
bytes - binary data

Repeated fields (arrays)
message Users {
  repeated User users = 1;
}

Optional fields
message User {
  string name = 1;
  optional string nickname = 2;
}

RPC Types

Unary RPC - single request/response
rpc GetUser(GetUserRequest) returns (User);

Server streaming - server sends stream
rpc ListUsers(Empty) returns (stream User);

Client streaming - client sends stream
rpc CreateUsers(stream User) returns (Summary);

Bidirectional streaming
rpc Chat(stream Message) returns (stream Message);

Generate Code

Install protoc compiler
brew install protobuf

Generate Node.js code
protoc --js_out=import_style=commonjs,binary:. \
  --grpc_out=. \
  --plugin=protoc-gen-grpc=grpc_tools_node_protoc_plugin \
  user.proto

Generate Python code
python -m grpc_tools.protoc -I. \
  --python_out=. \
  --grpc_python_out=. \
  user.proto