Protocol Buffers
How ApiHug use 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).
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:
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: "*"
};
}
}