OpenAPI 3.1 Output
Alpha — output is not yet stable. protoc-gen-openapiv3 is a new generator and the exact JSON shape it emits may change between minor releases as the mapping rules settle in response to user feedback. Specifically expect the encodings for oneofs, wrapper types, enums, and path-template expansion to evolve, and expect tooling-compatibility compromises (documented inline in the generator source) to be revisited as consumer OpenAPI 3.1 support matures. If you need a production-stable OpenAPI pipeline today, use protoc-gen-openapiv2.
protoc-gen-openapiv3 emits OpenAPI 3.1.0 JSON directly from google.api.http annotations. It is intentionally smaller in scope than protoc-gen-openapiv2 and does not consume the grpc.gateway.protoc_gen_openapiv2.options annotations. If you rely on those options, continue to use the v2 generator.
What it does
protoc-gen-openapiv3 walks every proto file it is asked to generate, finds services with HTTP bindings, and emits one OpenAPI 3.1.0 JSON document per proto file (foo.proto → foo.openapi.json). Files with no HTTP-bound services produce no output.
The output is deterministic and byte-stable across runs: paths are emitted in RPC declaration order, component schemas are sorted alphabetically, and response codes are emitted default-first then sorted.
What it does not do
The generator is deliberately opinionated. The following are not supported today:
- The
grpc.gateway.protoc_gen_openapiv2.optionsannotation set. - OpenAPI 2.0 / Swagger output (use
protoc-gen-openapiv2for that). - YAML output.
- Alternative naming strategies. Component names are always the fully-qualified proto name with the leading dot stripped (e.g.
lib.v1.Book). - Integer enums. Enums are always rendered as strings.
- Custom HTTP methods that OpenAPI 3.1 has no operation for. A
custombinding whosekindis not one ofGET,PUT,POST,DELETE,OPTIONS,HEAD,PATCHorTRACEis skipped. The match is case-sensitive, so akindofgetis skipped too.
Features can be added back as concrete needs emerge — if you want one of the above, please open an issue describing your use case.
Plugin options
disable_default_errors
By default, every operation gets an auto-injected default response entry pointing to the google.rpc.Status component schema. If you use a custom error handler that returns a different response shape, you can suppress this behaviour with the disable_default_errors option.
With buf (buf.gen.yaml):
version: v2
plugins:
- local: protoc-gen-openapiv3
out: .
opt:
- disable_default_errors=true
With protoc:
protoc -I. \
--openapiv3_out=. \
--openapiv3_opt=disable_default_errors=true \
path/to/your/service.proto
When set, neither the default response entry nor the google.rpc.Status component schema are emitted.
allow_delete_body
By default, a delete binding with a body is rejected, the same as in protoc-gen-grpc-gateway and protoc-gen-openapiv2. If you generate the gateway with allow_delete_body=true, pass the same option to this generator. The body is then emitted as the operation’s requestBody.
visibility_restriction_selectors
See Hiding fields, methods, services and enum values below.
Installation
go install github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv3@latest
Usage with buf
Add the plugin to your buf.gen.yaml:
version: v2
plugins:
- local: protoc-gen-openapiv3
out: .
Then run buf generate as usual. A .openapi.json file will appear next to each proto file that declares HTTP bindings.
Usage with protoc
protoc -I. \
--openapiv3_out=. \
path/to/your/service.proto
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 services, methods, fields and enum values. The generator drops any annotated element whose restriction labels do not overlap with the configured visibility_restriction_selectors. Elements without a VisibilityRule annotation are always emitted.
visibility_restriction_selectors can be declared multiple times to include multiple visibility restrictions in the output. For example, with buf:
version: v2
plugins:
- local: protoc-gen-openapiv3
out: .
opt:
- visibility_restriction_selectors=PREVIEW
- visibility_restriction_selectors=INTERNAL
or with protoc:
protoc --openapiv3_out=. \
--openapiv3_opt=visibility_restriction_selectors=PREVIEW \
--openapiv3_opt=visibility_restriction_selectors=INTERNAL \
./path/to/file.proto
The restriction labels are arbitrary. INTERNAL and PREVIEW are the conventional pair, but any label scheme works (ALPHA, BETA, RELEASED, …) as long as the annotations and the selector flag use the same vocabulary.
When a service is hidden, all of its methods are hidden along with it and the service’s tag is omitted from tags[]. When every field in a oneof group is hidden, the group’s “at most one set” constraint is also dropped.
Visibility annotations on fields used as HTTP path parameters (via google.api.http path templates) are ignored — the path template itself always exposes the parameter’s name. To hide an operation that takes a restricted input, apply google.api.method_visibility to the method (or google.api.api_visibility to the whole service) instead of annotating the path field.
If every value of an enum ends up hidden, the enum’s component schema is still emitted (a visible field may reference it) but falls back to an unconstrained type: string. A log line is written when this happens; broaden the selectors or hide the referring fields to silence it.
Mapping rules
The mapping from proto constructs to OpenAPI is fixed and summarised below.
Services and methods
| Proto | OpenAPI |
|---|---|
| Service | Tag (tags[]) plus tags on each operation |
| Method | Operation under a PathItem |
| Method leading comment | Operation summary / description |
Method deprecated=true | Operation deprecated: true |
| Additional bindings | Extra operations; operationId suffixed _<idx> |
The default operationId is <Service>_<Method>. When a method has multiple HTTP bindings, the first uses the bare ID and subsequent bindings append _1, _2, … so the spec remains valid. An operation_id set with openapiv3_operation is suffixed the same way.
The service’s tag is named after the service and described by its leading comment. The service-level openapiv3_tag annotation overrides it: a non-empty name renames the tag, which the service’s operations then use by default, and description, external_docs and extensions set the corresponding fields of the OpenAPI Tag Object. An operation-level openapiv3_operation.tags list still replaces the default for that operation.
import "protoc-gen-openapiv3/options/annotations.proto";
service BookService {
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_tag) = {
name: "Books"
description: "Manage the books in the library."
external_docs: {
description: "Library guide"
url: "https://example.com/docs/books"
}
};
rpc GetBook(GetBookRequest) returns (Book) {
option (google.api.http) = {get: "/v1/books/{id}"};
}
}
Parameters
- Path parameters from the
google.api.httpURL template becomein: pathparameters. Constrained path templates like
{name=shelves/*}are expanded into the OpenAPI URL verbatim: the literal prefix stays in the URL and each wildcard becomes its own OpenAPI parameter. This is required because the proto field binds to the full matched substring (e.g.shelves/abc), so a client following the OpenAPI URL must actually send/shelves/abcrather than just/abc. Examples:Proto template OpenAPI URL /v1/{name}/v1/{name}/v1/{name=shelves/*}/v1/shelves/{name}/v1/{name=shelves/*/books/*}/v1/shelves/{name}/books/{name_1}/v1/{name=files/**}/v1/files/{name}When a single proto field expands into multiple wildcards, the second and subsequent parameters are suffixed
_1,_2, … so the OpenAPI URL stays valid. All synthetic parameters point back at the same underlying proto field, which the grpc-gateway runtime reconstructs from the full matched substring at request time.- Fields that are neither path parameters nor part of the request body become
in: queryparameters. This also applies to nested fields: with/v1/{id.value},id.valueis only a path parameter, while the other fields ofidare still flattened into query parameters. When one member of aoneofis a path parameter or the body field, the other members of thatoneofare left out, since the runtime rejects them. google.protobuf.Structandgoogle.protobuf.Emptyquery parameters are typed as strings, since the runtime reads aStructas its JSON encoding and anEmptyas an empty value or{}.body="*"synthesises an inline object schema that includes every request field except path parameters.body="field"uses that single field’s type as the request body.- A map field becomes a single
name[keyType]query parameter (for examplelabels[string], sent as?labels[foo]=bar) whose schema is the value type. Maps whose values are messages are left out, since the runtime can’t read those from a query string. Well-known types are the exception, apart fromgoogle.protobuf.Anyandgoogle.protobuf.ListValue.
Header and cookie parameters
Protobuf has no notion of headers or cookies, so they are declared with openapiv3_operation.parameters. Each entry becomes an in: header or in: cookie Parameter Object, added after the path and query parameters on every binding of the method. type (string, number, integer or boolean; string when unset) and format set the parameter’s schema.
rpc ListBooks(ListBooksRequest) returns (ListBooksResponse) {
option (google.api.http) = {get: "/v1/books"};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
parameters: {
name: "X-Request-Id"
in: IN_HEADER
description: "Correlates the request across services."
format: "uuid"
}
parameters: {
name: "session"
in: IN_COOKIE
required: true
}
};
}
name and in are required. Two parameters of one operation may not share both a location and a name; header names are compared case-insensitively. A header named Accept, Content-Type or Authorization is refused, since OpenAPI 3.1.0 says such a parameter SHALL be ignored. Describe authorization with security schemes instead.
A parameter shared by many operations can be declared once under openapiv3_document.components.parameters and referenced by name with ref. It’s emitted under components.parameters and each use becomes a $ref: '#/components/parameters/<name>'.
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_document) = {
components: {
parameters: {
key: "TenantId"
value: {
name: "X-Tenant-Id"
in: IN_HEADER
required: true
}
}
}
};
rpc ListBooks(ListBooksRequest) returns (ListBooksResponse) {
option (google.api.http) = {get: "/v1/books"};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
parameters: {ref: "TenantId"}
};
}
A ref entry can’t set any other field, and must name a declared component. The duplicate check above uses the referenced parameter’s name and location.
Components belong to the document of the proto file that declares them. The generator writes one document per proto file, so a ref is resolved only against the components.parameters of its own file. A name declared in another file isn’t found and is reported as an undeclared component, and two files may declare the same name, since their documents are separate. Declare the parameter in each file that uses it.
The annotation only documents the parameter. By default the gateway forwards just the permanent HTTP request headers, Cookie among them, to gRPC metadata (see runtime.DefaultHeaderMatcher). Any other header reaches the backend only if the mux is built with a matcher that forwards it, using runtime.WithIncomingHeaderMatcher.
Examples
Header and cookie parameters, and response headers, can carry named Example Objects in examples, keyed by a name of your choosing. An example sets value (any JSON value) or external_value (a URL), not both, plus an optional summary and description. An example used in many places can be declared once under openapiv3_document.components.examples and referenced with ref, which renders as $ref: '#/components/examples/<name>'.
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_document) = {
components: {
examples: {
key: "Tenant"
value: {
summary: "A tenant"
value: {string_value: "acme"}
}
}
}
};
rpc ListBooks(ListBooksRequest) returns (ListBooksResponse) {
option (google.api.http) = {get: "/v1/books"};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
parameters: {
name: "X-Tenant-Id"
in: IN_HEADER
examples: {
key: "acme"
value: {ref: "Tenant"}
}
}
};
}
As with parameters, a ref entry can’t set any other field and is resolved only against the components of its own file.
Request bodies
You normally don’t need this. The generated request body already matches what the gateway decodes, so only set request_body when your server changes the body outside of the gateway, which should be rare. (Responses are different: overriding them is how you document alternative status codes.)
The request_body field of openapiv3_operation changes the request body the generator derives from the body of the HTTP rule. A description is added to it, and messages replaces its schema with the named proto messages, one referenced directly and several combined with oneOf, like the messages of a response. It’s applied to every binding of the method that has a body, so a GET in additional_bindings is left alone, but setting it on a method with no body at all is an error.
A request body shared by many operations can be declared once under openapiv3_document.components.request_bodies and referenced by name with ref, which becomes a $ref: '#/components/requestBodies/<name>'. A component request body must list its messages, since there’s no HTTP rule to derive a schema from. As with other components, a ref entry can’t set any other field and must name a request body declared in the same proto file.
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_document) = {
components: {
request_bodies: {
key: "Book"
value: {
description: "The book to store."
messages: "example.v1.Book"
}
}
}
};
rpc UpdateBook(UpdateBookRequest) returns (Book) {
option (google.api.http) = {
patch: "/v1/books/{id}"
body: "book"
};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
request_body: {ref: "Book"}
};
}
Replacing the schema only changes the document. The gateway still decodes the body into the field or message the HTTP rule names, so the messages should describe what it actually accepts.
Schemas
- Messages become component schemas under
#/components/schemas/. - Enums become string-valued component schemas.
repeatedfields producetype: array.- Map fields produce
type: objectwithadditionalProperties. - 64-bit integer fields are emitted as JSON strings, matching protojson.
- Well-known types are inlined, not referenced (see below).
- Field descriptions are populated from leading proto comments.
google.api.field_behaviormaps torequired,readOnly, andwriteOnlyon the parent schema.deprecated = trueon a field setsdeprecated: trueon the property.defaultandexamplesonopenapiv3_fieldoropenapiv3_schematake JSON values and are emitted as the JSON Schemadefaultandexampleskeywords. On a repeated field they describe the whole array.
int32 page_size = 2 [(grpc.gateway.protoc_gen_openapiv3.options.openapiv3_field) = {
default: {number_value: 50}
examples: [{number_value: 10}, {number_value: 100}]
}];
Oneofs
Every field inside a oneof appears as a normal property on the component schema, and each oneof group contributes an “at most one set” constraint on top of those properties. The constraint is expressed as a JSON Schema oneOf whose options are:
- a “none of the fields are set” guard of the form
{"not": {"anyOf": [{"required": ["fieldA"]}, {"required": ["fieldB"]}, ...]}}; - one
{"required": ["fieldN"]}option per field in the group.
Because oneOf matches exactly one sub-schema:
- zero fields set → only option 1 matches → passes,
- exactly one field set → only that field’s
requiredoption matches → passes, - two or more set → multiple
requiredoptions match → fails validation.
This matches proto3 oneof semantics, which allow either zero or one member to be set.
Messages with a single oneof group hoist the constraint directly onto the component schema’s oneOf. Messages with multiple groups wrap their group constraints in allOf so each group is enforced independently.
Single-field oneof groups produce a trivially-true constraint and are skipped for output hygiene. Synthetic proto3-optional oneofs are treated as regular optional fields (the proto compiler models optional string foo = 1; as a one-element synthetic oneof).
Well-known types
Well-known types are inlined as their protojson representation:
| WKT | Schema |
|---|---|
google.protobuf.Timestamp | string, format: date-time |
google.protobuf.Duration | string |
google.protobuf.FieldMask | string |
google.protobuf.StringValue | string |
google.protobuf.BytesValue | string, format: byte |
google.protobuf.Int32Value | integer, format: int32 |
google.protobuf.UInt32Value | integer, format: int64 |
google.protobuf.Int64Value | string, format: int64 |
google.protobuf.UInt64Value | string, format: uint64 |
google.protobuf.FloatValue | number, format: float |
google.protobuf.DoubleValue | number, format: double |
google.protobuf.BoolValue | boolean |
google.protobuf.Empty | object |
google.protobuf.Struct | object |
google.protobuf.Value | unconstrained |
google.protobuf.ListValue | array of unconstrained |
google.protobuf.NullValue | null |
google.protobuf.Any | object with @type plus open |
Wrapper types are intentionally not marked nullable. The strictly-correct JSON Schema 2020-12 form for google.protobuf.StringValue would be type: ["string", "null"], but no Go OpenAPI generator in the ecosystem handles that form today: openapi-generator-cli’s Go target produces unbuildable code, and oapi-codegen (including its experimental 3.1 fork) errors with unhandled Schema type: &[string null] on request bodies. Until tooling catches up, the generator describes wrappers as their underlying primitive. The grpc-gateway runtime still accepts a JSON null on the wire regardless, because protojson treats wrappers as optional.
RPCs returning google.protobuf.Empty emit a 200 with an object schema body ({}), matching what the grpc-gateway runtime actually writes on the wire. The HTTP-conventional 204 No Content would be more idiomatic but conflicts with runtime behaviour, so generated clients would reject valid responses.
RPCs returning google.api.HttpBody emit a 200 whose content is */* with no schema. The runtime writes the message’s data as the raw response body, with its content_type as the Content-Type, so the response can be of any media type.
Error responses
Every operation automatically gets a default response keyed to a component schema named google.rpc.Status with the standard code, message, and details[] fields. This matches what grpc-gateway returns on error paths. Use the disable_default_errors plugin option to suppress this behaviour when using a custom error handler.
To document more responses, list them under responses in the openapiv3_operation annotation, keyed by status code ("404"), range ("4XX") or "default". Each entry needs a description and can name the proto messages its body may hold. One message is referenced directly and several are combined with oneOf. Names are fully qualified, and messages named here get a component schema even if nothing else uses them. An entry replaces the generated response for the same key, so "default" swaps out the google.rpc.Status error response.
rpc DeleteFoo(DeleteFooRequest) returns (DeleteFooResponse) {
option (google.api.http) = {delete: "/v1/foo/{id}"};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
responses: {
key: "400"
value: {
description: "The foo is running or does not exist."
messages: ["example.v1.CannotDeleteError", "example.v1.NotFoundError"]
}
}
};
}
A response shared by many operations can be declared once under openapiv3_document.components.responses and referenced by name with ref. It’s emitted under components.responses, with its messages resolved to schemas the same way, and each use becomes a $ref: '#/components/responses/<name>'.
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_document) = {
components: {
responses: {
key: "NotFound"
value: {
description: "The resource does not exist."
messages: "example.v1.NotFoundError"
}
}
}
};
rpc GetFoo(GetFooRequest) returns (Foo) {
option (google.api.http) = {get: "/v1/foo/{id}"};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
responses: {
key: "404"
value: {ref: "NotFound"}
}
};
}
A ref entry can’t set any other field, and must name a response declared in the same proto file, like component parameters.
A response can also list the headers it sends, keyed by header name. A header takes the same description, required, deprecated, type and format fields as a header parameter. Names are compared case-insensitively, and Content-Type is refused because OpenAPI 3.1.0 ignores it there. Headers used by many responses can be declared under openapiv3_document.components.headers and referenced with ref, which becomes a $ref: '#/components/headers/<name>'. The same rules apply: a ref entry can’t set other fields and must name a declared header.
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_document) = {
components: {
headers: {
key: "Retry-After"
value: {
description: "Seconds to wait before retrying."
type: TYPE_INTEGER
}
}
}
};
rpc GetFoo(GetFooRequest) returns (Foo) {
option (google.api.http) = {get: "/v1/foo/{id}"};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
responses: {
key: "429"
value: {
description: "Too many requests."
headers: {
key: "Retry-After"
value: {ref: "Retry-After"}
}
}
}
};
}
Server streaming
For server-streaming RPCs, the grpc-gateway runtime writes one JSON object per message, separated by newlines, with each message wrapped as {"result": ...}. An error part-way through the stream is written as {"error": ...} with a google.rpc.Status body. The 200 response schema describes one of these chunks: an object titled Stream result of <message> with a result property holding the message schema (or the response_body field’s schema) and an error property referencing google.rpc.Status. The error property is omitted when disable_default_errors is set. google.api.HttpBody streams are written as raw bytes and are not wrapped, so they are described like a single google.api.HttpBody response.
Security schemes
Security schemes are declared once in the file-level openapiv3_document annotation, under components.security_schemes, and referenced by name from security requirements. A document-level security list applies to every operation in the file; an operation-level security list replaces it for that operation. Each entry in a security list is an alternative, and all schemes named within one entry must be satisfied together.
The fields map to the OpenAPI Security Scheme Object and Security Requirement Object. Generation fails if a scheme is missing a field the spec requires for its type, or if a requirement names a scheme that isn’t declared in the same file.
import "protoc-gen-openapiv3/options/annotations.proto";
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_document) = {
components: {
security_schemes: {
key: "BearerAuth"
value: {
type: TYPE_HTTP
scheme: "bearer"
bearer_format: "JWT"
}
}
security_schemes: {
key: "ApiKeyAuth"
value: {
type: TYPE_API_KEY
name: "X-API-Key"
in: IN_HEADER
}
}
security_schemes: {
key: "OAuth2"
value: {
type: TYPE_OAUTH2
flows: {
authorization_code: {
authorization_url: "https://example.com/oauth/authorize"
token_url: "https://example.com/oauth/token"
scopes: {
key: "read"
value: "Read access"
}
scopes: {
key: "write"
value: "Write access"
}
}
}
}
}
}
// Every operation requires a bearer token unless it says otherwise.
security: {
schemes: {
key: "BearerAuth"
value: {}
}
}
};
An operation can require different schemes, ask for OAuth2 scopes, or accept any of several alternatives:
rpc UpdateBook(UpdateBookRequest) returns (Book) {
option (google.api.http) = {
patch: "/v1/books/{book.id}"
body: "book"
};
// Either an OAuth2 token with the "write" scope, or an API key.
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
security: {
schemes: {
key: "OAuth2"
value: {scopes: "write"}
}
}
security: {
schemes: {
key: "ApiKeyAuth"
value: {}
}
}
};
}
To make authentication optional for an operation, add an empty requirement. It renders as {} in the operation’s security list:
rpc ListBooks(ListBooksRequest) returns (ListBooksResponse) {
option (google.api.http) = {get: "/v1/books"};
option (grpc.gateway.protoc_gen_openapiv3.options.openapiv3_operation) = {
security: {}
};
}
Mutual TLS (TYPE_MUTUAL_TLS) needs no other fields, and OpenID Connect (TYPE_OPEN_ID_CONNECT) needs open_id_connect_url.
Example
Given:
syntax = "proto3";
package example.v1;
import "google/api/annotations.proto";
service EchoService {
rpc Echo(EchoRequest) returns (EchoResponse) {
option (google.api.http) = {
post: "/v1/echo"
body: "*"
};
}
}
message EchoRequest { string message = 1; }
message EchoResponse { string message = 1; }
The generator emits echo.openapi.json with one POST /v1/echo operation, an EchoResponse component schema, and the auto-injected google.rpc.Status default error response. See protoc-gen-openapiv3/internal/genopenapi/testdata/simple_echo.openapi.json for the exact output.
Consuming the output
The generated spec validates as OpenAPI 3.1.0 and can be fed to any 3.1-aware tool, including openapi-generator-cli for client generation. An end-to-end example that runs a real grpc-gateway behind a generated Go client lives at examples/internal/integration/openapiv3.