Forum Discussion

bougar's avatar
bougar
Visitor
3 years ago

Best approach to define array with polymorphic types

 

Hi, I need to create an endpoint which accepts an array of animals. I would like to choose the best option to define array with polymorphic types. I have found the following two approach, but I am open to new ones:

Approach with inheritance:

 

 

paths:
  /pets:
    post:
      requestBody:
        content:
          application/json:
            schema:
              type: array
              items:
                $ref: '#/components/schemas/Pet'
      responses:
        '200':
          description: OK
components:
  schemas:
    Pet:
      oneOf:
        - $ref: '#/components/schemas/Cat'
        - $ref: '#/components/schemas/Dog'
    discriminator:
      propertyName: type
      mapping:
          cat: "#/components/schemas/Cat"
          dog: "#/components/schemas/Dog"
    Dog:
      - type: object
        properties:
          type:
            type: string
            enum:
              - dog
          bark:
            type: string
    Cat:
      - type: object
        properties:
          type:
            type: string
            enum:
              - cat
          hunts:
            type: boolean
            hunts:
              type: boolean
            age:
              type: integer

 

 

 

OneOf approach:

 

 

paths:
  /pets:
    post:
      requestBody:
        content:
          application/json:
            schema:
              type: array
              items:
                $ref: '#/components/schemas/Pet'
      responses:
        '200':
          description: OK
components:
  schemas:
    Pet:
      type: object
      properties:
        type:
          type: string
        enum:
          - cat
          - dog
      discriminator:
        propertyName: type
        mapping:
          cat: "#/components/schemas/Cat"
          dog: "#/components/schemas/Dog"
    Dog:
      allOf:
        - $ref: "#/components/schemas/Pet"
        - type: object
          properties:
            bark:
              type: string
    Cat:
      allOf:
        - $ref: "#/components/schemas/Pet"
        - type: object
          properties:
            hunts:
              type: boolean
            age:
              type: integer

 

 

 

Thanks by your time 🙂

No RepliesBe the first to reply