Skip to content

Protocol Buffer (Protobuf)

Shivam Gupta edited this page Dec 24, 2021 · 3 revisions

Protocol Buffer

Protobuf is the most commonly used IDL (Interface Definition Language) for gRPC. It's where you basically store your data and function contracts in the form of a proto file.

Protocol Buffers offer typed variables where JSON does not, this simply helps programmers with the type of the field they are reading from the data file — in JSON sometimes we have to do extra checks to decide if the field is a number or not.

Protocol Buffers represent data in the binary format while JSON is a text-based format. This means compromising on human-readability for the sake of better encoding/decoding performance. Since the payload takes much less space in binary format this also helps with the bandwidth.

message Person {
    required string name = 1;
    required int32 id = 2;
    optional string email = 3;
}

As this is in the form of a contract, both the client and server need to have the same proto file. The proto file acts as the intermediary contract for client to call any available functions from the server.

Protobuf also has it owns mechanisms, unlike a usual REST API that just sends over strings of JSON as bytes. These mechanisms allow the payload to be much smaller and enable faster performance.

Example:- consider the greet.proto file

  • Defines a Greeter service.
  • The Greeter service defines a SayHello call.
  • SayHello sends a HelloRequest message and receives a HelloReply message:
syntax = "proto3";

option csharp_namespace = "GrpcGreeter";

package greet;

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply);
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings.
message HelloReply {
  string message = 1;
}

Demo:

Proto.mp4
Clone this wiki locally