我正在尝试使用Swagger记录REST API . 我们API的简化JSON响应如下:
{
"data": {
"type": "person"
"id": "1"
"attributes": {
"name": "Joe"
"age": 32
...
}
"links": {
...
}
}
}
要么
{
"data": {
"type": "job"
"id": "22"
"attributes": {
"name": "Manager"
"location": "Somewhere"
...
}
"links": {
...
}
}
}
他们对成功GET的Swagger定义可能如下所示:
'200':
description: OK.
schema:
type: object
properties:
data:
type: object
properties:
id:
type: string
type:
type: string
attributes:
$ref: '#/definitions/person'
要么
'200':
description: OK.
schema:
type: object
properties:
data:
type: object
properties:
id:
type: string
type:
type: string
attributes:
$ref: '#/definitions/job'
在我们的Swagger文件中可能有很多重复 . 是否可以定义这些响应来共享公共部分?即我不想输入或复制/粘贴此部分数次:
'200':
description: OK.
schema:
type: object
properties:
data:
type: object
properties:
id:
type: string
type:
type: string
我无法看到这如何使用鉴别器字段或使用$ ref .
1 回答
您可以使用
allOf
进行合成(与discriminator
一起可以进行继承,但它不是真正的函数)allOf
与模式或引用数组一起使用,它将创建一个包含数组中所有定义的所有属性的新定义 .鉴于您希望某些定义共享
id
和type
属性,它就是这样完成的:在这个例子中:
Person = SharedDefinition内联定义
Job = SharedDefinition JobSubDefinition
更多关于这一点
Writing OpenAPI (Swagger) Specification Tutorial – Part 4 – Advanced Data Modeling(披露:我写了这个教程)
OpenAPI Specification#models-with-composition