我正在为API编写Swagger文档,并且一个端点返回许多嵌套对象和参数。
但是,有一个返回的数组不返回常规参数。相反,它返回两个包含参数的匿名对象。
"balanceDisplaySettings": [
{
"type": "Balance",
"label": "Current",
"visible": true,
"primary": false
},
{
"type": "AvailableBalance",
"label": "Available",
"visible": true,
"primary": true
}
]
YAML
swagger: '2.0'
schemes:
- https
consumes:
- application/json
produces:
- application/json
paths:
"/Path/":
responses:
'200':
description: OK
schema:
type: object
properties:
balanceDisplaySettings:
type: array
items:
type: object
properties:
type:
type: "Balance"
description: description
label:
type: "Available"
description: description
visible:
type: boolean
description: description
primary:
type: boolean
description: description
type: object
properties:
type:
type: "AvailableBalance"
description: description
label:
type: "Available"
description: description
visible:
type: boolean
description: description
primary:
type: boolean
description: description
看看描述请求体的swagger文档,似乎无法处理没有名称的对象。
如何(使用YAML)在Swagger-UI中记录这种类型的响应主体?
答案 0 :(得分:2)
对象数组定义如下:
type: array
items:
type: object
properties:
prop1:
type: string
prop2:
type: integer
# etc.
在您的示例中,响应包含具有属性balanceDisplaySettings
的对象,并且此属性包含对象数组。这可以定义如下:
paths:
/Path:
get:
responses:
200:
description: OK
schema:
type: object
properties:
balanceDisplaySettings:
type: array
items:
type: object
properties:
type:
type: string
label:
type: string
visible:
type: boolean
primary:
type: boolean
请注意,架构定义了响应结构,这意味着您无需在任何地方指定实际值("Balance"
,"AvailableBalance"
等)。但是,如果要在Swagger UI中显示帖子(包含2个对象的数组)中的示例,可以像下面这样添加它:
balanceDisplaySettings:
type: array
items:
type: object
properties:
type:
type: string
label:
type: string
visible:
type: boolean
primary:
type: boolean
example: # <-- example of array of 2 objects
- type: Balance
label: Current
visible: true
primary: false
- type: AvailableBalance
label: Available
visible: true
primary: true
最后,您可能希望拆分内联嵌套模式以使规范更加模块化。
paths:
/Path:
get:
responses:
200:
description: OK
schema:
$ref: '#/definitions/MyResponseObject'
# |
definitions: # |
# TODO: better name # |
MyResponseObject: # <--------------+
type: object
properties:
balanceDisplaySettings:
type: array
items:
$ref: '#/definitions/BalanceDisplaySetting'
example: # |
- type: Balance # |
label: Current # |
visible: true # |
primary: false # |
- type: AvailableBalance # |
label: Available # |
visible: true # |
primary: true # |
# |
BalanceDisplaySetting: # <--------+
type: object
properties:
type:
type: string
example: Balance
label:
type: string
example: Current
visible:
type: boolean
boolean:
type: boolean