OpenAPI discriminator oneOf default

Viewed 1475

Given the following OpenAPI YAML, do we always need to define petType while creating Pet?

Can I by default create a pet of type Dog without specifying petType? Is there some way to do this with OpenAPI?

Pet:
 oneOf:
  - $ref: '#/components/schemas/Cat'
  - $ref: '#/components/schemas/Dog'
  - $ref: '#/components/schemas/Lizard'
  discriminator:
     propertyName: petType
2 Answers

do we always need to define petType while creating Pet

Yes. As explained in the Discriminator Object section of the OpenAPI Specification (emphasis mine):

a discriminator MAY act as a "hint" to ... selection of the matching schema ... We can then describe exactly which field tells us which schema to use:
...
The expectation now is that a property with name petType MUST be present in ... payload, and the value will correspond to the name of a schema defined in the OAS document.

I had a similar problem myself, and I was able to work out the following solution:

Pet:
  x-field-extra-annotation: '@com.fasterxml.jackson.annotation.JsonTypeInfo(
      use = com.fasterxml.jackson.annotation.JsonTypeInfo.Id.NAME,
      include = com.fasterxml.jackson.annotation.JsonTypeInfo.As.PROPERTY,
      property = "petType", visible = true,
      defaultImpl = Dog.class)'
  oneOf:
    - $ref: '#/components/schemas/Cat'
    - $ref: '#/components/schemas/Dog'
    - $ref: '#/components/schemas/Lizard'
  discriminator:
    propertyName: petType

I used 6.0.1 version of the OpenAPI generator.

Just in case, here is the link to the documentation where I found many other helpful solutions: https://openapi-generator.tech/docs/generators/spring

Related