microsoft / typespec

https://typespec.io/
MIT License
4.51k stars 216 forks source link

openapi 3.1 - support null types #5010

Open chrisradek opened 1 week ago

chrisradek commented 1 week ago

Open API 3.0 supports nullable types by setting the nullable: true field on schemas that contain a type.

Open API 3.1 drops support for the nullable field, instead going all in on adding type: "null" from the Json Schema spec.

The majority of the time when we want to emit type: "null" it is because a model property is nullable - it can be set to some type or null. It is relatively rarer that a model property would be only settable to null.

Since in Open API 3.1 type can also be an array now, support for nullable types can be done in 2 ways:

  1. by adding a { type: "null" } sub-schema as part of an anyOf.
  2. Adding "null" to the schema's type array.

There are subtle differences between these 2 options due to how Json Schema validation works. One example is with enums. To support nullable enums, either of these would be valid:

Option1:
  anyOf:
    - type: string
      enum:
        - foo
        - bar
    - type: "null"
Option2:
  type:
    - string
    - "null"
  enum:
    - foo
    - bar
    - null

Note that in Option 2, null needs to be part of the enum list.

Currently our JSON Schema emitter emits option 1.

markcowl commented 3 days ago

est: 3