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

标签 swagger swagger-2.0 swagger-editor openapi

我正在寻找一种优雅的方式来定义可以使用 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.x

您的场景可以使用 OpenAPI 3.x 来描述。 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

更多信息:

关于swagger - 编写使用多种内容类型的 swagger 文档,例如application/json AND application/x-www-form-urlencoded (不重复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42287298/

相关文章:

yaml - Swagger 不呈现请求体

java - Swagger:如何在 swagger 文件中引用 Document 对象?

python - Swagger 将自定义属性添加到参数定义

c# - AddMvc/AddSwaggerGen 和 UseMvc/UseSwagger(UI) 之间的顺序

javascript - 有没有办法在 swagger-ui 3.* 中只呈现特定的 api 端点?

java - 使用 Swagger 注释显示自定义 HashMap 键

swagger - 从 Swagger 规范生成 nodejs

swagger - 有没有办法从 C++ 代码生成一个 swagger 规范文件?

node.js - 如何覆盖 swagger.yaml 文件的位置?

yaml - Swagger 文档错误 `Should be object`