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'
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With