【问题标题】:In Swagger, how to define an API that consumes a file along with a schema parameter?在 Swagger 中,如何定义一个使用文件和模式参数的 API?
【发布时间】:2015-09-22 19:14:03
【问题描述】:

我正在尝试使用 Swagger 定义一个接受实际文件和描述文件内容的模式对象的 API。这是 Swagger YAML 的 sn-p。但是,它不会在 Swagger 编辑器中验证。

/document:
  post:
    summary: Api Summary
    description: Api Description
    consumes:
      - multipart/form-data
    parameters:
      - name: documentDetails
        in: formData
        description: Document Details
        required: true
        schema:
          $ref: '#/definitions/Document'
      - name: document
        in: formData
        description: The actual document
        required: true
        type: file

Swagger 编辑器抛出以下验证错误:

Swagger 错误:数据与“oneOf”中的任何架构都不匹配

我错过了什么吗?或者这不是 Swagger 支持的功能吗?

【问题讨论】:

  • 想要做同样的事情,上传一个带有 json doc 的文件,服务器与 doc 一起存储。你有没有想出一个可以分享的解决方法?谢谢。

标签: swagger swagger-2.0 openapi


【解决方案1】:

这在 OpenAPI 3.0 中是可能的,但在 OpenAPI/Swagger 2.0 中是不可能的。

OpenAPI/Swagger 2.0 不支持表单数据中的对象。表单参数可以是原始值、原始数组和文件,但不能是对象。所以你的例子不能用 OpenAPI 2.0 来描述。

在 OpenAPI 3.0 中,您可以使用:

paths:
  /document:
    post:
      summary: Api Summary
      description: Api Description
      requestBody:
        required: true
        content:
          multipart/form-data:

            # Form parameters from 2.0 become body schema properties in 3.0
            schema:
              type: object
              properties:

                # Schema properties correspond to individual parts
                # of the multipart request
                document:
                  # In 3.0, files are binary strings
                  type: string
                  format: binary
                  description: The actual document

                documentDetails:
                  $ref: '#/components/schemas/Document'
                  # The default Content-Type for objects is `application/json`
              required:
                - document
                - documentDetails

3.0 规范的相关部分:
Considerations for File Uploads
Special Considerations for multipart Content

【讨论】:

  • 在我们的例子中,我们使用 string 类型和 description 属性来表示该类型必须匹配模式中的特定模型。为了完美,但在我们迁移到 OpenApi 3.0 之前一直有效
【解决方案2】:

swagger 不支持 formData 中的 type 'object',只能作为 body 参数。

【讨论】:

    【解决方案3】:

    使用 Swagger 2.0 是不可能的,您只能将其作为类型 'file' 读取,

    https://swagger.io/docs/specification/2-0/file-upload/

    在相关说明中,请注意 Swagger 2.0 也不支持上传文件数组,但 Open API 3.0 支持。

    https://github.com/OAI/OpenAPI-Specification/issues/254

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 2020-08-04
      • 2021-11-14
      • 2020-04-13
      • 1970-01-01
      相关资源
      最近更新 更多