gRPC Service Definition in Protobuf

Define gRPC services with unary RPC methods in protobuf. Covers service declaration, request/response patterns, and method naming conventions.

Services & RPCs

Detailed Explanation

Defining gRPC Services

A service in protobuf defines a set of RPC (Remote Procedure Call) methods that a server implements and a client can call. These definitions are the foundation of gRPC APIs.

syntax = "proto3";

package user.v1;

service UserService {
  // Unary RPCs: single request, single response
  rpc GetUser(GetUserRequest) returns (GetUserResponse);
  rpc CreateUser(CreateUserRequest) returns (CreateUserResponse);
  rpc UpdateUser(UpdateUserRequest) returns (UpdateUserResponse);
  rpc DeleteUser(DeleteUserRequest) returns (DeleteUserResponse);
  rpc ListUsers(ListUsersRequest) returns (ListUsersResponse);
}

message GetUserRequest {
  int64 user_id = 1;
}

message GetUserResponse {
  User user = 1;
}

message CreateUserRequest {
  string name = 1;
  string email = 2;
  string role = 3;
}

message CreateUserResponse {
  User user = 1;
}

message UpdateUserRequest {
  int64 user_id = 1;
  string name = 2;
  string email = 3;
}

message UpdateUserResponse {
  User user = 1;
}

message DeleteUserRequest {
  int64 user_id = 1;
}

message DeleteUserResponse {}

message ListUsersRequest {
  int32 page_size = 1;
  string page_token = 2;
}

message ListUsersResponse {
  repeated User users = 1;
  string next_page_token = 2;
}

message User {
  int64 id = 1;
  string name = 2;
  string email = 3;
  string role = 4;
}

Service Design Patterns

Separate Request/Response types: Each RPC should have its own request and response message types, even if they seem identical to other RPCs. This enables independent evolution without breaking changes.

Naming conventions:

  • Service name: PascalCase ending with Service (e.g., UserService)
  • Method name: PascalCase verb-noun (e.g., GetUser, ListUsers)
  • Request message: {MethodName}Request
  • Response message: {MethodName}Response

Package versioning: Use versioned packages like user.v1 to support API evolution. When making breaking changes, create user.v2 instead of modifying v1.

Code Generation

Running protoc with a language-specific gRPC plugin generates:

  • Server interface/abstract class with one method per RPC
  • Client stub with methods that handle connection, serialization, and error handling
  • Message classes for all request/response types

Use Case

Building a microservice API layer where services need well-defined contracts with automatic code generation for multiple programming languages (Go, Java, Python, TypeScript, etc.).

Try It — Protobuf Definition Parser

Open full tool