Customizing OpenAPI Output

In proto comments

You can provide comments directly in your Protocol Buffer definitions and they will be translated into comments in the generated OpenAPI definitions:

  1. message MyMessage {
  2. // This comment will end up direcly in your Open API definition
  3. string uuid = 1 [(grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {description: "The UUID field."}];
  4. }

Using proto options

You can define options on your Protocol Buffer services, operations, messages, and field definitions to customize your Open API output. For instance, to customize the OpenAPI Schema Object for messages and fields:

  1. import "protoc-gen-openapiv2/options/annotations.proto";
  2. message ABitOfEverything {
  3. option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_schema) = {
  4. json_schema: {
  5. title: "A bit of everything"
  6. description: "Intentionaly complicated message type to cover many features of Protobuf."
  7. required: ["uuid", "int64_value", "double_value"]
  8. }
  9. external_docs: {
  10. url: "https://github.com/grpc-ecosystem/grpc-gateway";
  11. description: "Find out more about ABitOfEverything";
  12. }
  13. example: "{\"uuid\": \"0cf361e1-4b44-483d-a159-54dabdf7e814\"}"
  14. extensions: {
  15. key: "x-irreversible";
  16. value {
  17. bool_value: true;
  18. }
  19. }
  20. };
  21. string uuid = 1 [(grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {description: "The UUID field."}];
  22. }

Operations can also be customized:

  1. service ABitOfEverythingService {
  2. rpc Delete(grpc.gateway.examples.internal.proto.sub2.IdMessage) returns (google.protobuf.Empty) {
  3. option (google.api.http) = {
  4. delete: "/v1/example/a_bit_of_everything/{uuid}"
  5. };
  6. option (grpc.gateway.protoc_gen_openapiv2.options.openapiv2_operation) = {
  7. security: {
  8. security_requirement: {
  9. key: "ApiKeyAuth";
  10. value: {}
  11. }
  12. security_requirement: {
  13. key: "OAuth2";
  14. value: {
  15. scope: "read";
  16. scope: "write";
  17. }
  18. }
  19. }
  20. extensions: {
  21. key: "x-irreversible";
  22. value {
  23. bool_value: true;
  24. }
  25. }
  26. };
  27. }
  28. }

Swagger Extensions can be added as key-value pairs to the options. Keys must begin with x- and values can be of any type listed here. For example:

  1. extensions: {
  2. key: "x-amazon-apigateway-authorizer";
  3. value {
  4. struct_value {
  5. fields {
  6. key: "type";
  7. value {
  8. string_value: "token";
  9. }
  10. }
  11. fields {
  12. key: "authorizerResultTtlInSeconds";
  13. value {
  14. number_value: 60;
  15. }
  16. }
  17. }
  18. }
  19. }

Please see this a_bit_of_everything.proto for examples of the options being used.

Using google.api.field_behavior

Google provides an field option for defining the behavior of fields that is also supported:

  1. import "google/api/field_behavior.proto";
  2. message MyMessage {
  3. string a_required_field = 1 [(google.api.field_behavior) = REQUIRED];
  4. }

The following options are used in the Open API output:

  • REQUIRED - marks a field as required
  • OUTPUT_ONLY - marks a field as readonly

Google defines a couple of other options - OPTIONAL, IMMUTABLE, INPUT_ONLY - that are not currently used. OPTIONAL support is currently under discussion in this issue.

For IMMUTABLE and INPUT_ONLY fields, there is an open issue in the Open API specification for adding functionality for write-once or immutable fields to the spec.

Using go templates in proto file comments

Use Go templates in your proto file comments to allow more advanced documentation such as:

  • Documentation about fields in the proto objects.
  • Import the content of external files (such as Markdown).

How to use it

By default this function is turned off, so if you want to use it you have to add the use_go_templates option:

  1. --openapiv2_out . --openapiv2_opt use_go_templates=true

or:

  1. --openapiv2_out=use_go_templates=true:.

Example script

Example of a bash script with the use_go_templates flag set to true:

  1. $ protoc -I. \
  2. --go_out . --go-grpc_out . \
  3. --grpc-gateway_out . --grpc-gateway_opt logtostderr=true \
  4. --openapiv2_out . \
  5. --openapiv2_opt logtostderr=true \
  6. --openapiv2_opt use_go_templates=true \
  7. path/to/my/proto/v1/myproto.proto

Example proto file

Example of a proto file with Go templates. This proto file imports documentation from another file, tables.md:

  1. service LoginService {
  2. // Login
  3. //
  4. // {{.MethodDescriptorProto.Name}} is a call with the method(s) {{$first := true}}{{range .Bindings}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{.HTTPMethod}}{{end}} within the "{{.Service.Name}}" service.
  5. // It takes in "{{.RequestType.Name}}" and returns a "{{.ResponseType.Name}}".
  6. //
  7. // {{import "tables.md"}}
  8. rpc Login (LoginRequest) returns (LoginReply) {
  9. option (google.api.http) = {
  10. post: "/v1/example/login"
  11. body: "*"
  12. };
  13. }
  14. }
  15. message LoginRequest {
  16. // The entered username
  17. string username = 1;
  18. // The entered password
  19. string password = 2;
  20. }
  21. message LoginReply {
  22. // Whether you have access or not
  23. bool access = 1;
  24. }

The content of tables.md:

  1. ## {{.RequestType.Name}}
  2. | Field ID | Name | Type | Description |
  3. | ----------- | --------- | --------------------------------------------------------- | ---------------------------- | {{range .RequestType.Fields}}
  4. | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}}
  5. ## {{.ResponseType.Name}}
  6. | Field ID | Name | Type | Description |
  7. | ----------- | --------- | ---------------------------------------------------------- | ---------------------------- | {{range .ResponseType.Fields}}
  8. | {{.Number}} | {{.Name}} | {{if eq .Label.String "LABEL_REPEATED"}}[]{{end}}{{.Type}} | {{fieldcomments .Message .}} | {{end}}

OpenAPI output

SwaggerUI

This is how the OpenAPI file would be rendered in Swagger UI.

Screenshot OpenAPI file in SwaggerUI

Postman

This is how the OpenAPI file would be rendered in Postman.

Screenshot OpenAPI file in Postman

For a more detailed example of a proto file that has Go, templates enabled, see the examples.

Other plugin options

A comprehensive list of OpenAPI plugin options can be found here. Options can be passed via protoc CLI:

  1. --openapiv2_out . --openapiv2_opt bar=baz,color=red

Or, with buf in buf.gen.yaml:

  1. - name: openapiv2
  2. out: foo
  3. opt: bar=baz,color=red

Merging output

If your protobuf definitions are spread across multiple files, the OpenAPI plugin will create a file for each .proto input. This may make sense for Go bindings, since they still share a package space, but fragmenting OpenAPI specifications across multiple files changes the schema itself.

To merge disparate .proto inputs into a single OpenAPI file, use the allow_merge and merge_file_name options.

opt: allow_merge=true,merge_file_name=foo will result in a single foo.swagger.json. Note that you may need to set the generation strategy to all when merging many files:

  1. - name: openapiv2
  2. out: foo
  3. strategy: all
  4. opt: allow_merge=true,merge_file_name=foo

Enums as integers

To generate enums as integers instead of strings, use enums_as_ints.

opt: enums_as_ints=true will result in:

  1. {
  2. "name": "enumValue",
  3. "description": " - Example enums",
  4. "in": "query",
  5. "required": false,
  6. "type": "int",
  7. "enum": [
  8. 0,
  9. 1
  10. ],
  11. "default": 0
  12. },

Omitting the default value of enums

If you define enum types with non default value such as declaring 0 value with UNKNOWN and want to omit the default value from generated swagger file, use omit_enum_default_value. This option also applies if enums_as_ints option is enalbled to generate enums as integer.

opt: omit_enum_default_value=true will result in:

Input Example:

  1. enum enumValue {
  2. UNKNOWN = 0;
  3. FOO = 1;
  4. }

Output json:

  1. {
  2. "name": "enumValue",
  3. "description": " - Example enums",
  4. "in": "query",
  5. "required": false,
  6. "type": "string",
  7. "enum": [
  8. "FOO"
  9. ]
  10. },

Hiding fields, methods, services and enum values

If you require internal or unreleased fields and APIs to be hidden from your API documentation, google.api.VisibilityRule annotations can be added to customize where they are generated. Combined with the option visibility_restriction_selectors, overlapping rules will appear in the OpenAPI output.

visibility_restriction_selectors can be declared multiple times as an option to include multiple visibility restrictions in the output. e.g. if you are using buf:

  1. version: v1
  2. plugins:
  3. - name: openapiv2
  4. out: .
  5. opt:
  6. - visibility_restriction_selectors=PREVIEW
  7. - visibility_restriction_selectors=INTERNAL

or with protoc

  1. protoc --openapiv2_out=. --openapiv2_opt=visibility_restriction_selectors=PREVIEW --openapiv2_opt=visibility_restriction_selectors=INTERNAL ./path/to/file.proto

Elements without google.api.VisibilityRule annotations will appear as usual in the generated output.

These restrictions and selectors are completely arbitrary and you can define whatever values or hierarchies you want. In this example we use INTERNAL and PREVIEW, but INTERNAL, ALPHA, BETA, RELEASED, or anything else could be used if you wish.

Note: Annotations are only supported on Services, Methods, Fields and Enum Values.

opt: visibility_restriction_selectors=PREVIEW will result in:

Input Example:

  1. service Echo {
  2. rpc EchoInternal(VisibilityRuleSimpleMessage) returns (VisibilityRuleSimpleMessage) {
  3. option (google.api.method_visibility).restriction = "INTERNAL";
  4. option (google.api.http) = {
  5. get: "/v1/example/echo_internal"
  6. };
  7. }
  8. rpc EchoInternalAndPreview(VisibilityRuleSimpleMessage) returns (VisibilityRuleSimpleMessage) {
  9. option (google.api.method_visibility).restriction = "INTERNAL,PREVIEW";
  10. option (google.api.http) = {
  11. get: "/v1/example/echo_internal_and_preview"
  12. };
  13. }
  14. }
  15. message VisibilityRuleSimpleMessage {
  16. enum VisibilityEnum {
  17. UNSPECIFIED = 0;
  18. VISIBLE = 1;
  19. INTERNAL = 2 [(google.api.value_visibility).restriction = "INTERNAL"];
  20. PREVIEW = 3 [(google.api.value_visibility).restriction = "INTERNAL,PREVIEW"];
  21. }
  22. string internal_field = 1 [(google.api.field_visibility).restriction = "INTERNAL"];
  23. string preview_field = 2 [(google.api.field_visibility).restriction = "INTERNAL,PREVIEW"];
  24. VisibilityEnum an_enum = 3;
  25. }

Output json:

  1. {
  2. "paths": {
  3. "/v1/example/echo_internal_and_preview": {
  4. "get": {
  5. "summary": "EchoInternalAndPreview is a internal and preview API that should be visible in the OpenAPI spec.",
  6. "operationId": "VisibilityRuleEchoService_EchoInternalAndPreview",
  7. "responses": {
  8. "200": {
  9. "description": "A successful response.",
  10. "schema": {
  11. "$ref": "#/definitions/examplepbVisibilityRuleSimpleMessage"
  12. }
  13. },
  14. "default": {
  15. "description": "An unexpected error response.",
  16. "schema": {
  17. "$ref": "#/definitions/rpcStatus"
  18. }
  19. }
  20. },
  21. "parameters": [
  22. {
  23. "name": "previewField",
  24. "in": "query",
  25. "required": false,
  26. "type": "string"
  27. },
  28. {
  29. "name": "anEnum",
  30. "in": "query",
  31. "required": false,
  32. "type": "string",
  33. "enum": [
  34. "UNSPECIFIED",
  35. "VISIBLE",
  36. "PREVIEW"
  37. ],
  38. "default": "UNSPECIFIED"
  39. }
  40. ],
  41. "tags": [
  42. "VisibilityRuleEchoService"
  43. ]
  44. }
  45. }
  46. }
  47. }

For a more in depth example see visibility_rule_echo_service.proto and the following output files for different values of visibility_restriction_selectors:

Path parameters

When defining HTTP bindings with path parameters that contain multiple path segments, as suggested by the Google AIPs, the path parameter names are numbered to avoid generating duplicate paths in the OpenAPI file.

For example, consider:

  1. service LibraryService {
  2. rpc GetShelf(GetShelfRequest) returns (Shelf) {
  3. option (google.api.http) = {
  4. get: "/v1/{name=shelves/*}"
  5. };
  6. }
  7. rpc GetBook(GetBookRequest) returns (Book) {
  8. option (google.api.http) = {
  9. get: "/v1/{name=shelves/*/books/*}"
  10. };
  11. }
  12. }
  13. message GetShelfRequest {
  14. string name = 1;
  15. }
  16. message GetBookRequest {
  17. string name = 1;
  18. }

This will generate the following paths:

  • /v1/{name}
  • /v1/{name_1}

To override the path parameter names, annotate the field used as path parameter:

  1. message GetShelfRequest {
  2. string name = 1 [(grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {field_configuration: {path_param_name: "shelfName"}}];
  3. }
  4. message GetBookRequest {
  5. string name = 1 [(grpc.gateway.protoc_gen_openapiv2.options.openapiv2_field) = {field_configuration: {path_param_name: "bookName"}}];
  6. }

This will instead generate the following paths:

  • /v1/{shelfName}
  • /v1/{bookName}

Note that path parameters in OpenAPI does not support values with /, as discussed in Support for path parameters which can contain slashes #892, so tools as Swagger UI will URL encode any / provided as parameter value. A possible workaround for this is to write a custom post processor for your OAS file to replace any path parameter with / into multiple parameters.

Output format

By default the output format is JSON, but it is possible to configure it using the output_format option. Allowed values are: json, yaml. The output format will also change the extension of the output files.

For example, if using buf:

  1. - name: openapiv2
  2. out: pkg
  3. opt: output_format=yaml

Input example:

  1. syntax = "proto3";
  2. package helloproto.v1;
  3. option go_package = "helloproto/v1;helloproto";
  4. import "google/api/annotations.proto";
  5. service EchoService {
  6. rpc Hello(HelloReq) returns (HelloResp) {
  7. option (google.api.http) = {
  8. get: "/api/hello"
  9. };
  10. }
  11. }
  12. message HelloReq {
  13. string name = 1;
  14. }
  15. message HelloResp {
  16. string message = 1;
  17. }

Output:

  1. swagger: "2.0"
  2. info:
  3. title: helloproto/v1/example.proto
  4. version: version not set
  5. tags:
  6. - name: EchoService
  7. consumes:
  8. - application/json
  9. produces:
  10. - application/json
  11. paths:
  12. /api/hello:
  13. get:
  14. operationId: EchoService_Hello
  15. responses:
  16. "200":
  17. description: A successful response.
  18. schema:
  19. $ref: '#/definitions/v1HelloResp'
  20. default:
  21. description: An unexpected error response.
  22. schema:
  23. $ref: '#/definitions/rpcStatus'
  24. parameters:
  25. - name: name
  26. in: query
  27. required: false
  28. type: string
  29. tags:
  30. - EchoService
  31. definitions:
  32. protobufAny:
  33. type: object
  34. properties:
  35. '@type':
  36. type: string
  37. additionalProperties: {}
  38. rpcStatus:
  39. type: object
  40. properties:
  41. code:
  42. type: integer
  43. format: int32
  44. message:
  45. type: string
  46. details:
  47. type: array
  48. items:
  49. $ref: '#/definitions/protobufAny'
  50. v1HelloResp:
  51. type: object
  52. properties:
  53. message:
  54. type: string