OpenAPI multiple types inside an array
Asked Answered
N

1

23

I'm having trouble defining a reusable schema component using OpenAPI 3 which would allow for an array that contains multiple types. Each item type inherits from the same parent class but has specific child properties. This seems to work alright in the model view on SwaggerHub but the example view doesn't show the data correctly.

TLDR; Is there a way to define an array containing different object types in OpenAPI 3?

Response:
  allOf:
    - $ref: '#/components/schemas/BaseResponse'
    - type: object
      title: A full response
      required:
      - things
      properties:
        things:
          type: array
          items:
            anyOf:
              - $ref: '#/components/schemas/ItemOne'
              - $ref: '#/components/schemas/ItemTwo'
              - $ref: '#/components/schemas/ItemThree'
Nola answered 5/12, 2017 at 15:8 Comment(0)
A
28

Your spec is correct. It's just that example rendering for oneOf and anyOf schemas is not yet supported in Swagger UI. You can track this issue for status updates:

Multiple responses using oneOf attribute do not appear in UI

The workaround is to manually add an example alongside the oneOf/anyOf schema or to the parent schema:

        things:
          type: array
          items:
            anyOf:
              - $ref: '#/components/schemas/ItemOne'
              - $ref: '#/components/schemas/ItemTwo'
              - $ref: '#/components/schemas/ItemThree'
          # Note that array example is on the same
          # level as `type: array`
          example:
            - foo: bar        # Example of ItemOne
              baz: qux
            - "Hello, world"  # Example of ItemTwo
            - [4, 8, 15, 16, 23, 42]  # Example of ItemThree
Analiese answered 5/12, 2017 at 15:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.