I am writing an OpenAPI (Swagger) definition where a query parameter can take none, or N values, like this:
/path?sort=field1,field2
How can I write this in OpenAPI YAML?
I tried the following, but it does not produce the expected result:
- name: sort
in: query
schema:
type: string
enum: [field1,field2,field3]
allowEmptyValue: true
required: false
description: Sort the results by attributes. (See http://jsonapi.org/format/1.1/#fetching-sorting)
Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
The payload format is similar to query parameters. multipart/form-data allows submitting binary data as well as multiple media types in a single message (for example, image and JSON). Each form field has its own section in the payload with internal HTTP headers. multipart requests are commonly used for file uploads.
The enum keyword is used to restrict a value to a fixed set of values. It must be an array with at least one element, where each element is unique.
A query parameter containing a comma-separated list of values is defined as an array. If the values are predefined, then it's an array of enum.
By default, an array may have any number of items, which matches your "none or more" requirement. If needed, you can restrict the number of items using minItems
and maxItems
, and optionally enforce uniqueItems: true
.
The parameter definition would look as follows. collectionFormat: csv
indicates that the values are comma-separated, but this is the default format so it can be omitted.
parameters:
- name: sort
in: query
type: array # <-----
items:
type: string
enum: [field1, field2, field3]
collectionFormat: csv # <-----
required: false
description: Sort the results by attributes. (See http://jsonapi.org/format/1.1/#fetching-sorting)
collectionFormat: csv
from OpenAPI 2.0 has been replaced with style: form
+ explode: false
. style: form
is the default style for query parameters, so it can be omitted.
parameters:
- name: sort
in: query
schema:
type: array # <-----
items:
type: string
enum: [field1, field2, field3]
required: false
description: Sort the results by attributes. (See http://jsonapi.org/format/1.1/#fetching-sorting)
explode: false # <-----
I think there's no need for allowEmptyValue
, because an empty array will be effectively an empty value in this scenario. Moreover, allowEmptyValue
is not recommended for use since OpenAPI 3.0.2 "as it will be removed in a future version."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With