1

我正在尝试使用 Swagger 记录具有对象数组参数的 API POST 调用。但是当我尝试在 Swagger UI 中对其进行测试时,似乎explode: trueencoding:filters. 这是我的代码:

openapi: 3.0.2
info:
  description: >-
    My API
  version: 1.0.0
  title: My API
tags:
  - name: myApi
    description: my API
paths:
  /myApi/getList:
    post:
      tags:
        - myApi
      summary: gets a list
      description: gets a list
      requestBody:
        required: true
        content:
          application/x-www-form-urlencoded:
            schema:
              type: object
              properties:
                sourceId:
                  type: integer
                  description: the source id
               filters:
                  type: array
                  items:
                    $ref: '#/components/schemas/Filter'
            encoding:
              filters:
                contentType: application/json
                explode: true
      responses:
        '200':
          description: successful operation
          content:
            application/json:
              schema:
                type: array
                items:
                  type: string
        '500':
          description: error
components:
  schemas:
    Filter: 
      type: object
      properties:
        field:
          type: string
          description: the name of the field for this filter
        selection:
          type: array
          items:
            type: string
            description: the name of a selected value of the filter field
      required: [attribUniqueName, selection]

如果我用作参数,例如

sourceId: 1

filters: [
  {
    "field": "product",
    "selection": ["Prod A", "Prod B"]
  },
  {
    "field": "country",
    "selection": ["USA", "France"]
  }
]

然后 Swagger UI 生成一个调用(如果我为了更好的可读性而省略了 URL 编码):

sourceId=1&filters={"field":"product","selection":["Prod A","Prod B"]},{"field":"country","selection":["USA","France"]}

我怎样才能让它生产

sourceId=1&filters={"field":"product","selection":["Prod A","Prod B"]}&filters={"field":"country","selection":["USA","France"]}

反而?

“编码对象”的OpenAPI 3.0.2 文档指出explode“如果请求正文媒体类型不是 application/x-www-form-urlencoded,则应忽略属性”。但我们在这里使用 application/x-www-form-urlencoded。还是文档有误,应该说明“当前对象的内容类型”而不是“请求正文媒体类型”?但是,我会假设得到一个真正的数组作为参数值,即

sourceId=1&filters=[{"field":"product","selection":["Prod A","Prod B"]},{"field":"country","selection":["USA","France"]}]

如果重要:我使用的是 Swagger UI 版本 3.24.3。

4

1 回答 1

2

您的代码看起来不错,实际问题是encoding Swagger UI 尚不支持

有关 Github 上的相关问题,请参见此处。它有一个字符串数组的示例,而不是像您的情况那样的对象数组,但可能只要它不适用于字符串,它也不适用于对象。

于 2020-02-06T10:36:20.083 回答