Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
425 views
in Technique[技术] by (71.8m points)

Swagger: take one or more values from enum

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

OpenAPI 2.0

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)

OpenAPI 3.0

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."


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...