google / google/gnostic

protoc-gen-openapi: Nullable for fields in OpenAPI

Open
#347 6 comments 9 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
2.3k
Forks
279
PR merge metrics
No merged PRs in 30d

Description

Would it be possible to add an option to protoc-gen-openapi to generate proto3 fields labeled as `optional` to OpenAPI object properties with label `nullable: true`?

For example this proto file:
```proto
syntax = "proto3";

message Foo {
optional int32 bar = 1;
}
```
when generated by protoc-gen-openapi with some new option (e.g. proto3-optional-nullable=true) would be generated as OpenAPI spec:
```yaml
openapi: 3.0.3
components:
schemas:
Foo:
properties:
bar:
type: integer
format: int32
nullable: true
```

If I understand it correctly:
- All fields in proto3 are optional
- When a field in proto3 is not explicitly set, it is set with default (zero) value when (un)marshaling from/into wire format.
- To distinguish in proto3 whether a field was explicitly set with some value or not (_explicit field presence_), we can use the `optional` label
- then the generated stubs use for instance in case of Go *int32 instead of int32 so the `nil` value represents whether the field was explicitly set
- By default all object properties in OpenAPI3.0 are optional (but unlike proto3 can be marked as required).
- When an optional object property is not set in OpenAPI3.0, no default value is used during (de)serialization from/into JSON format. The object property is just not present.
- However, the property presence can be also 'simulated' by using the same approach as in protobuf -> setting a `null` value to the object property. But to make it work, the property must be labeled as nullable.

The similar feature is supported in [grpc-gateway/protoc-gen-openapiv2](https://github.com/grpc-ecosystem/grpc-gateway/blob/b5ae278bc454073dfcd3672e9ed367c3816fec1a/protoc-gen-openapiv2/main.go#L36) - it supports option to generate object properties in OAS2 as nullable -> the main motivation for this option is that some other tools generating code from the (generated) OpenAPI spec cannot handle default (null) values set during the transition from proto3 marshaled wire format to openapi json.

This issue is related to #275.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.