1. Protocol Buffers
  2. Protocol Buffers Option

This article will explain how ApiHug leverages the extension capabilities of Protocol Buffers using options and utilizes Protocol Buffers as the language for defining the OpenAPI Specification (OAS).

Protocol Buffers Option

Option Options can be used in proto files, messages, enums and services. An option can be a protobuf defined option or a custom option. For more information, see Options in the language guide.

option = "option" optionName  "=" constant ";"
optionName = optionNamePart { "." optionNamePart }
optionNamePart = { ident | "(" ["."] fullIdent ")" }

Example:

option java_package = "com.example.foo";

protobuf options:

  • google.protobuf.FileOptions
  • google.protobuf.ServiceOptions
  • google.protobuf.MethodOptions
  • google.protobuf.MessageOptions
  • google.protobuf.FieldOptions
  • google.protobuf.EnumOptions
  • google.protobuf.EnumValueOptions

Extension Support OAS

By utilizing Protobuf’s options, we can add our own custom options and generate code to handle parameters in the proto file accordingly. This allows us to perform operations such as adding meta information for example validation for messages.

The extension of Protocol Buffers options enables support for The OpenAPI Specification possible.

In fact, there have been pioneers who have adopted similar approaches. For example, the Google Open API Protos project utilizes pure Proto methods to define internal APIs, while gRPC-Gateway takes it a step further by translating RESTful HTTP APIs into gRPC.

A real google API example:

service AdMobApi {
  option (google.api.default_host) = "admob.googleapis.com";
  option (google.api.oauth_scopes) =
      "https://www.googleapis.com/auth/admob.report";

  // Gets information about the specified AdMob publisher account.
  rpc GetPublisherAccount(GetPublisherAccountRequest)
      returns (PublisherAccount) {
    option (google.api.http) = {
      get: "/v1/{name=accounts/*}"
    };
    option (google.api.method_signature) = "name";
  }
}

A real gRPC-Gateway example:

service WrappersService {
  rpc Create(Wrappers) returns (Wrappers) {
    option (google.api.http) = {
      post: "/v1/example/wrappers"
      body: "*"
    };
  }
}

Refer

  1. gRPC-Gateway is a plugin of protoc. It reads a gRPC service definition and generates a reverse-proxy server which translates a RESTful JSON API into gRPC.
  2. Google Open API Protos public Google APIs that support both REST and gRPC protocols.
  3. The OpenAPI Specification