在 Swagger 中描述 json 参数

Describing a json parameter in Swagger

问题

根据 this and this Swagger 支持复杂参数,但是当我尝试描述一个 json 参数时,Swagger Editor 显示以下问题:

Could not render ParameterRow, see the console.

预期行为

Json 对象作为参数。

YAML

openapi: "3.0.0"
info:
  version: 1.0.0
  title: Trackmeeasy API
paths:
  /getLabelUrl.action:
    post:
      parameters:
        - in: query
          name: filter
          content:
            application/json:
              schema:
                type: object
                properties:
                  type:
                    type: string
                  color:
                    type: string
      responses:
        '200':
          description: OK

重现...

  1. 复制 yaml
  2. 转到http://editor.swagger.io
  3. 粘贴 yaml
  4. 看到错误

截图

OpenAPI Swagger UI 3.23.8+Swagger Editor 支持带有 content 的 3.0 参数3.6.34+.


如果您使用 UI 或编辑器的早期版本,您可以使用 this workaround 获得 "try it out" 支持 - 即定义参数为 type: string 并添加一个 example 的 JSON 数据。您无法为查询字符串描述 JSON 架构,但 "try it out" 可以。

      parameters:
        - in: query
          name: filter
          schema:
            type: string                           # <-------
          example: '{"type":"foo","color":"bar"}'  # <-------


注意:如果您正在设计新的 API 而不是描述现有的 API,您应该 post 复杂的数据,例如作为 JSON 个对象,在请求正文中改为:

openapi: 3.0.0
...
paths:
  /getLabelUrl.action:
    post:
      requestBody:    # <-----
        content:
          application/json:
            schema:
              type: object
              ...

或者如果使用查询参数更合适,请考虑 "flattening" 将对象转换为键=值对,例如:

POST /getLabelUrl.action?type=foo&color=bar

此序列化策略是使用 style: formexplode: true 定义的。有关查询参数序列化的更多示例,请参阅 here

openapi: 3.0.0
...
paths:
  /getLabelUrl.action:
    post:
      parameters:
        - in: query
          name: filter
          schema:
            type: object
            properties:
              type:
                type: string
              color:
                type: string

          # style=form + explode=true is the default serialization strategy
          # so you can omit this
          style: form
          explode: true