Defining a gRPC Service with Protocol Buffers

Home » EN » Blog » Defining a gRPC Service with Protocol Buffers


* This post is the third in the series on gRPC


The first step in building a gRPC service is to create the service interface definition with the methods that are exposed by that service along with the input parameters and return types.

Defining a gRPC Service with Protocol Buffers

gRPC uses protocol buffers (protocol buffers or protobufs) as IDL to define the service interface. Protocol buffers are an extensible, language- and platform-independent mechanism for serializing structured data. The service interface definition is specified in a proto file, which is nothing more than a plain text file with a .proto extension. The gRPC services are defined in an ordinary protocol buffer format, with the RPC method parameters and return types specified as protocol buffer messages. Since the service definition is an extension of the protocol buffer specification, a special gRPC plug-in is used to generate code from its .proto file.

A proto file, which is nothing more than a plain text file with a .proto extension, is used to generate code from the .proto file.

In the example, the DrinkInfo service interface, called DrinkService, is defined using protobuf as shown in the following snippet. The DrinkService consists of a service interface definition in which we specify the remote methods(addCreate and Get), their input and output parameters, and the definition of the type (or message formats) of those parameters.

syntax = "proto3";

message DrinkMessage {
    string id = 1;
    string name = 2;
    string desc = 3;
}

message DrinkMessages {
    repeated DrinkMessage drinks = 1;
}

message Empty {}

service DrinkService {
    rpc addCreate (DrinkMessage) returns (DrinkMessage);
    rpc Get (Empty) returns (DrinkMessages);
}

As you can see, a service is a collection of methods (for example, addProduct and getProduct) that can be invoked remotely. Each method has input parameters and return types that we define as part of the service or that can be imported into the protobuf definition.

The input and return parameters can be a user-defined type (e.g., DrinkMessage and DrinkMessages types) or a standard data type such as string. These types are structured as messages, where each message is a small logical record of information containing a series of name-value pairs. These fields are name-value pairs with unique field numbers (e.g., string id = 1) that are used to identify their fields in the binary format of the message.

This service definition is used to build the server and client side of a gRPC application. In the next post I will give you more details of the gRPC server implementation.

I take this opportunity to recommend some books that may interest you:



Learning HTTP/2: A Practical Guide for Beginners

Stephen Ludin


The Design of Web APIs

Arnaud Lauret