How can excluding types for array items be defined with OpenAPI/Swagger?

Viewed 2418

Swagger documentation explains how to define arrays that contain mixed types, such as ["foo", 5, -2, "bar"]. But, how can I define that an array must contain either one type of items (strings, ["foo", "bar"]) or another (integers, [5, -2])?

I've tried this, but Swagger UI can't render it, so I guess that it's wrong:

      oneOf:
        - items:
          - $ref: '#/components/schemas/SchemaA'
        - items:
          - $ref: '#/components/schemas/SchemaB'
1 Answers

First of all, remember that oneOf is only supported in OpenAPI 3.0 (openapi: 3.0.0) but not in OpenAPI 2.0 (swagger: '2.0').

Your scenario can be defined using oneOf like so:

oneOf:
  - type: array
    items:
      type: string
  - type: array
    items:
      type: integer
  - type: array
    items:
      $ref: '#/components/schemas/SchemaA'

In vanilla JSON Schema, type: array can be moved out of oneOf and placed alongside oneOf but I'm not sure if OpenAPI allows this (the OpenAPI Specification is unclear on this).

type: array
oneOf:
  - items:
      type: string
  - items:
      type: integer
  - items:
      $ref: '#/components/schemas/SchemaA'


I've tried this, but Swagger UI can't render it

Currently, Swagger UI does not automatically generate examples for oneOf and anyOf schemas (see this issue). The workaround is to add an example alongside oneOf manually:

example: [1, 2, 3]  # <------
oneOf:
  - type: array
    items:
      type: string
  - type: array
    items:
      type: integer
  - type: array
    items:
      $ref: '#/components/schemas/SchemaA'
Related