Arl*_*rlo 6 swagger swagger-ui swagger-editor
我正在为 API 编写 Swagger 文档,一个端点返回许多嵌套的对象和参数。
然而,有一个返回的数组不返回常规参数。相反,它返回两个包含参数的匿名对象。
"balanceDisplaySettings": [
{
"type": "Balance",
"label": "Current",
"visible": true,
"primary": false
},
{
"type": "AvailableBalance",
"label": "Available",
"visible": true,
"primary": true
}
]
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
查看描述请求正文的 swagger 文档,似乎无法处理没有名称的对象。
我如何(使用 YAML)在 Swagger-UI 中记录这种类型的响应主体?
对象数组的定义如下:
type: array
items:
type: object
properties:
prop1:
type: string
prop2:
type: integer
# etc.
Run Code Online (Sandbox Code Playgroud)
在您的示例中,响应包含一个具有属性的对象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
Run Code Online (Sandbox Code Playgroud)
请注意,该架构定义的响应结构,这意味着你不需要指定实际值("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
Run Code Online (Sandbox Code Playgroud)
最后,您可能希望拆分内联嵌套模式以使规范更加模块化。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7757 次 |
| 最近记录: |