我们的 API 有这样的端点,支持来自 query
的参数。来自 body
同时,通过合并这两组参数。
例如:
/foo?param1=value1
body: {
param2=value2
}
结果参数集将包含两个,
param1
和 param2
.此端点可用作:
/foo?param1=value1¶m2=value2
或者
/foo
body: {
param1=value1,
param2=value2
}
有没有办法在 Swagger 中指定这种“二元性”?
UPD
我想我应该将参数定义为两者:
body
和 query
in:
- body
- query
最佳答案
您需要定义查询参数和正文参数,但将它们都标记为可选。使用操作description
解释客户端可以在查询字符串或正文中发送参数。
swagger: '2.0'
...
paths:
/foo:
post:
consumes:
- application/json
parameters:
- in: query
name: param1
type: string
required: false
- in: query
name: param2
type: string
required: false
- in: body
name: body
required: false
schema:
type: object
properties:
param1:
type: string
param2:
type: string
使用 OpenAPI 3.0,它更优雅一点,您可以重用相同的
schema
对于查询字符串和请求正文:openapi: 3.0.0
...
paths:
/foo:
post:
parameters:
# This expands into ?param1=value1¶m2=value2&...
- in: query
name: parameters
required: false
schema:
$ref: '#/components/schemas/Parameters'
style: form
explode: true
requestBody:
required: false
content:
application/json:
schema:
$ref: '#/components/schemas/Parameters'
responses:
'200':
description: OK
components:
schemas:
Parameters:
type: object
properties:
param1:
type: string
param2:
type: string
Swagger UI 用户注意事项:从 UI v. 3.11.0 开始,似乎还不支持将对象序列化为查询字符串。
关于查询和/或正文中的 Swagger 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49013630/