Reputation: 39
I understand how to represent the array in query parameters with Swagger 2.0:
?list=x&list=y
Is it possible to represent an array in Swagger 2.0 using an indexed style?
?list[0]=x&list[1]=y
Upvotes: 2
Views: 635
Reputation: 97991
list[0]
, list[1]
, list[2]
... list[N]
must be defined as separate query parameters. There's no way to define list
as a single array-type parameter and have it serialized the way you want.
Note that this approach only works for fixed-sized arrays whose maximum size is known in advance.
parameters:
- in: query
name: list[0]
type: string
- in: query
name: list[1]
type: string
One approach is to define list[0]
, list[1]
, etc. as separate query parameters (like in the OpenAPI 2.0 example above). This approach is suitable for fixed-sized arrays whose maximum size is known in advance.
parameters:
- in: query
name: list[0]
schema:
type: string
- in: query
name: list[1]
schema:
type: string
Another approach - suitable for arrays of unknown size - is to define such an array using free-form query parameters. The limitation of this approach is that it allows arbitrary parameter names - not just list[n]
but also abcde
. However, you can provide a description
explaining that the parameter names must be in the format list[n]
, and also provide an example
value for documentation purposes.
parameters:
- in: query
name: params # arbitrary name, not used in the actual query string
description: >-
Parameter names must be in the format `list[n]`
where `n` is an integer starting from 0.
schema:
type: object
example:
list[0]: x
list[1]: y
list[2]: z
In Swagger UI, enter the query parameters in the JSON object (not array) format, like so:
{
"list[0]": "x",
"list[1]": "y",
"list[2]": "z"
}
Swagger UI will convert this into the following query string (before URL encoding):
?list[0]=x&list[1]=y&list[2]=z
OAS 3.1 takes us one step forward. You would still use the free-form query approach but narrow it down by using the new patternProperties
keyword to specify a regular expression for the allowed parameter names (e.g. ^list\[\d+\]$
).
# openapi: 3.1.0
parameters:
- in: query
name: params # arbitrary name, not used in the actual query string
description: >-
Parameter names must be in the format `list[n]`
where `n` is an integer starting from 0.
schema:
type: object
patternProperties: # <--------
^list\[\d+\]$:
type: string
additionalProperties: false
example:
list[0]: x
list[1]: y
list[2]: z
Upvotes: 1