notAChance
notAChance

Reputation: 1430

OpenAPI - how to set a property as string or array, and if array abide by #ref

I have the below openapi spec piece:

 *           type:
 *             - string
 *             - array
 *           items:
 *             $ref: '#/components/schemas/objectType'

I have an input which might be an empty string or an array of objects. When I generate the above model it gives me below type:

string | any[]

However, what I need is:

string | objectType[]

What am I doing wrong?

Upvotes: 3

Views: 3199

Answers (1)

CollinD
CollinD

Reputation: 7573

I think you want to make use of the oneOf property. Here's a small example doc that I think does what you're looing for.

note: oneOf is an array of objects each declaring a whole schema type, rather than an array of types adjacent to an items declaration as in your code. This nesting is important, and allows for expression of arbitrarily complex union types.

openapi: 3.0.1
info:
  title: Test API
  version: 1.0.0
paths:
  /foo:
    get:
      responses:
        200:
          description: "OK"
          content:
            application/json:
              schema:
                oneOf:         # <--- create a union type
                - type: string # <--- string |
                - type: array  # <--- FooResponseObject[]
                  items:
                    $ref: "#/components/schemas/FooResponseObject"
components:
  schemas:
    FooResponseObject:
      type: object
      properties:
        id:
          type: string
        name:
          type: string

Upvotes: 4

Related Questions