Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenAPI multiple types inside an array

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'
like image 850
Bobbake4 Avatar asked Dec 05 '17 15:12

Bobbake4


People also ask

How do you declare an array of strings in Swagger?

YAML. Firstly, we start by specifying the array of strings in Swagger using YAML notation. In the schema section, we include type: array with items String.

What is oneOf in OpenAPI?

OpenAPI 3.0 provides several keywords which you can use to combine schemas. You can use these keywords to create a complex schema, or validate a value against multiple criteria. oneOf – validates the value against exactly one of the subschemas. allOf – validates the value against all the subschemas.


1 Answers

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
like image 75
Helen Avatar answered Sep 19 '22 13:09

Helen