robtot
robtot

Reputation: 1031

Swagger/OpenAPI: What are valid ways to define arrays in query parameters?

I have seen multiple ways to define arrays in query parameters in Swagger- and OpenAPI specifications. Are all the below examples valid? Are there more valid options?

Example 1:

...
{
    "name": "example",
    "in": "query",
    "type": "array",
    "items": {
        "type": "string"
    }
}
...

Example 2:

...
{
    "name": "example",
    "in": "query",
    "type": "array",
    "items": {
        "properties": {
            "username": {
                "type": "string"
            },
            "password": {
                "type": "string"
            }
        }
    }
}
...

Example 3:

...
{
    "name": "example",
    "in": "query",
    "type": "array",
    "schema": {
        "items": {
            "type": "string"
        }
    }
}
...

Example 4:

...
{
    "name": "example",
    "in": "query",
    "type": "array",
    "schema": {
        "items": {
            "properties": {
                "username": {
                    "type": "string"
                },
                "password": {
                    "type": "string",
                }
            }
        }
    }
}
...

Are there more options?

Thanks!

Upvotes: 2

Views: 4570

Answers (1)

Helen
Helen

Reputation: 97991

Examples 1 and 3 are basically the same, and so are examples 2 and 4. The difference is the version of the OpenAPI Specification used: examples without schema are OpenAPI 2.0 syntax (swagger: 2.0); with schema - OpenAPI 3 syntax (openapi: 3.x.x). The schema keyword wraps type-related keywords in OpenAPI 3.0 parameter definitions.

Both OpenAPI 2.0 and 3 only support arrays of primitives in query parameters.


Example 1 is a valid OpenAPI 2.0 parameter definition.

In OpenAPI 3, the same parameter would be defined with a schema containing the type and items:

// openapi: 3.0.0

{
    "name": "example",
    "in": "query",
    "schema": {    // <--------------
      "type": "array",
      "items": {
        "type": "string"
      }
    }
}

Example 2 - not valid. This is an OpenAPI 2.0 definition, and OAS 2 explicitly disallows arrays of objects in query parameters. It only supports arrays of primitives and arrays of arrays.

Example 3 - almost, but not quite. This seems to be OpenAPI 3, in which case type: array must be inside the schema, like so:

// openapi: 3.0.0

{
    "name": "example",
    "in": "query",
    "schema": {
      "type": "array",    // <--------------
      "items": {
        "type": "string"
      }
    }
}

Example 4 - again, type: array must be inside the schema to make this definition syntactically correct. However, this example defines an array of objects, for which the serialization behavior is not defined. So this example is actually undefined behavior.

Upvotes: 2

Related Questions