Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a mixed-type array (with different element types) in OpenAPI 2.0?

I trying to map the following JSON to an OpenAPI 2.0 (Swagger 2.0) YAML definition, and I am not sure how to set mixed array types into my schema:

{
  "obj1": [
     "string data",
     1
    ]
}

Now, my OpenAPI definition has:

schema:
  object1:
    type: array
    items:
      type: string

but this doesn't allow integers inside the array.

Is there a way to define a mixed type array?

like image 632
Rjk Avatar asked Aug 01 '16 03:08

Rjk


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.

How do you declare an empty array in swagger?

You can specify an empty array [] as an example for your array schema. This will override the default examples values generated by Swagger UI. Save this answer.

What are the three primary sections in a Swagger specification?

A Swagger version defines the overall structure of an API specification – what you can document and how you document it. Then, you need to specify the API info – title , description (optional), version (API version, not file revision or Swagger version).


1 Answers

The answer depends on which version of the OpenAPI Specification you use.

OpenAPI 3.1

type can be a list of types, so you can write your schema as:

# openapi: 3.1.0

obj1:
  type: array
  items:
    type: [string, integer]
    # or if nulls are allowed:
    # type: [string, integer, 'null']

OpenAPI 3.0.x

Mixed types are supported in OpenAPI 3.0 using oneOf / anyOf and optionally nullable: true to also allow nulls.

# openapi: 3.0.1

obj1:
  type: array
  items:
    oneOf:
      - type: string
        nullable: true  # If nulls are allowed
      - type: integer

OpenAPI 2.0

OpenAPI 2.0 (Swagger 2.0) does not really support mixed-type array and parameters. The most you can do is to use a typeless schema {} for items, which means the items can be anything (except null) – numbers, objects, strings, etc. You cannot specify the exact types for items, but you can add an example of an array with different item types.

# swagger: '2.0'

obj1:
  type: array
  items: {}  # <--- means "any type" (except null)
  example:
    - string data
    - 1

Note: Typeless schema {} can only be used in body parameters and response schemas. Path, header and form parameters require a primitive type for array items.

like image 73
Helen Avatar answered Sep 19 '22 09:09

Helen