我正在寻找一种优雅的方式来定义可以使用 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/json
和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
更多信息:
关于swagger - 编写使用多种内容类型的 swagger 文档,例如application/json AND application/x-www-form-urlencoded (不重复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42287298/