7

我正在寻找一种优雅的方式来定义一个可以使用 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值必须是字符串,而不是数组。

有什么好主意吗?

4

1 回答 1

9

开放API 2.0

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

开放API 3.0

您的场景可以使用 OpenAPI 3.0 来描述。关键字用于定义操作接受的requestBody.content.<media-type>各种媒体类型,例如application/jsonand application/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

更多信息:

于 2017-04-11T17:06:28.063 回答