Skip to content

Proper use of polymorphism / inheritance in Open API 3 #2116

@PierrePrimot

Description

@PierrePrimot

I just want to make a correct specification with basic inheritance anywhere in the schemas, be able to show it properly in the swagger editor and generate some code with it, but I can't. I am clearly missing something in Open API 3.

In the specification document (3.0.2), an example uses oneOf, and optionally the Discriminator block :

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

In this scenario, the only constraint that Cat, Dog and Lizard must satisfy is the mandatory field petType, and a predetermined value.
Then, one can read :

To avoid redundancy, the discriminator MAY be added to a parent schema
definition, and all schemas comprising the parent schema in an allOf
construct may be used as an alternate schema.

I find it nice since it offers a proper use of the natural inheritance of the 3 entities :

components:
  schemas:
    Pet:
      type: object
      required:
      - petType
      properties:
        petType:
          type: string
      discriminator:
        propertyName: petType
        mapping:
          dog: Dog
    Cat:
      allOf:
      - $ref: '#/components/schemas/Pet'
      - type: object
        # all other properties specific to a `Cat`
        properties:
          name:
            type: string
etc

By the way, the spec is a bit ambiguous with

The discriminator object is legal only when using one of the composite
keywords oneOf, anyOf, allOf

Pet does not contains any of these keywords !

However, this second example does not show the consequences on the MyResponseType block.

  1. Does it stay the same ? If so, what should be generated, say, in Java ? A MyResponseType and a Pet classes ? What should the MyResponseType class look like ?
  2. Should MyResponseType be removed from the file, and Pet used instead ? If so, the swagger editor is not capable of tracing the subtypes anymore...
  3. Then, should we add the oneOf to the Pet schema, so that the swagger editor can display the subtypes ? I've tried, it works, and validators say it's Open API 3 compliant, but warn that a cycle gets in the way. It seems to me that this would be formally wrong : an http body with a Cat (petType Cat) with all the Cat and Dog properties would validate because of the oneOf Cat/Dog inherited from Pet. Am I right to interprete it this way ?

It may be correlated with [#403]

Metadata

Metadata

Assignees

Labels

clarificationrequests to clarify, but not change, part of the specdiscriminator

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions