编写使用多种内容类型的 swagger 文档,例如application/json AND application/x-www-form-urlencoded(w/o 重复)

Write swagger doc that consumes multiple content types e.g. application/json AND application/x-www-form-urlencoded (w/o duplication)

我正在寻找一种优雅的方式来定义可以使用 JSON 数据和表单数据的 api。以下代码片段有效,但它并不优雅,并且需要在后端使用各种丑陋的代码。有没有更好的方法来定义它?

现在有效的是:

paths:
  /pets:
    post:
      consumes:
      - application/x-www-form-urlencoded
      - application/json
      parameters:
      - name: nameFormData
        in: formData
        description: Updated name of the pet
        required: false
        type: string
      - name: nameJSON
        in: body
        description: Updated name of the pet
        required: false
        type: string

我希望它如何工作的基本想法:

paths:
  /pets:
    post:
      consumes:
      - application/x-www-form-urlencoded
      - application/json
      parameters:
      - name: name
        in: 
        - formData
        - body
        description: Updated name of the pet
        required: true
        type: string

但这不起作用,因为 in 值必须是字符串,而不是数组。

有什么好主意吗?

OpenAPI 2.0

在 OpenAPI 2.0 中,无法描述这一点。表单和主体参数是互斥的,因此操作可以具有表单数据或 JSON 主体,但不能同时具有两者。一种可能的解决方法是使用两个单独的端点 - 一个用于表单数据,另一个用于 JSON - 如果这在您的场景中可以接受。

OpenAPI 3.0

您的场景可以使用 OpenAPI 3.0 来描述。 requestBody.content.<media-type> 关键字用于定义操作接受的各种媒体类型,例如 application/jsonapplication/x-www-form-urlencoded,以及它们的模式。媒体类型可以具有相同的架构或不同的架构。

openapi: 3.0.0
...
paths:
  /pets:
    post:
      requestBody:
        required: true
        content:

          application/json:
            schema:
              $ref: '#/components/schemas/Pet'

          application/x-www-form-urlencoded:
            schema:
              $ref: '#/components/schemas/Pet'

       responses:
         '200':
            description: OK

components:
  schemas:
    Pet:
      type: object
      properties:
        name:
          type: string
          description: Updated name of the pet
      required:
        - name

更多信息: