我正在寻找一种优雅的方式来定义可以使用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
值必须是字符串,而不是数组。
有什么好主意吗?
答案 0 :(得分:4)
在OpenAPI 2.0中,没有办法描述它。表单和主体参数是互斥的,因此操作可以具有表单数据或JSON主体,但不能同时具有两者。一种可能的解决方法是拥有两个单独的端点 - 一个用于表单数据,另一个用于JSON - 如果在您的方案中可接受的话。
您可以使用OpenAPI 3.0描述您的方案。 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
更多信息: