swagger - 在 Swagger 中描述一个 json 参数

标签 swagger openapi

问题

根据 thisthis 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. 查看错误

截图

Screenshot

最佳答案

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


如果您使用较早版本的 UI 或编辑器,您可以使用 this workaround获得“尝试一下”支持——即将参数定义为 type: string 并添加 JSON 数据的 example。您失去了描述查询字符串的 JSON 模式的能力,但“试试看”会起作用。

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


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

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

或者如果使用查询参数更合适,请考虑将对象“扁平化”为键=值对,例如:

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

关于swagger - 在 Swagger 中描述一个 json 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51588708/

相关文章:

asp.net-core - 获取 ASP Core 的 XML 注释输出文件位置

rest - REST API 具有 `required` 响应属性意味着什么?

rest - 从 WSDL/XML 以编程方式生成 Swagger YAML Open API 规范

angular - Swagger/OpenAPI : How to integrate generation of typescript/angular client in build process?

java - 如何在 sprinddoc 中添加一个操作未引用的类?

rest - 使用 springfox Swagger 自定义文档的端点

laravel - 如何用 swagger 包装 Laravel 资源

kotlin - 尝试在 gradle kotlindsl 中包含 swagger-codegen

c# - 为 ASP.NET Core 中的未绑定(bind)参数添加 swagger 参数

swagger - OAS3 指定的服务版本控制