Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 346
notAChance Avatar asked Jun 05 '26 21:06

notAChance


1 Answers

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
like image 154
CollinD Avatar answered Jun 07 '26 09:06

CollinD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!