在 Swagger 文档中合并定义
Combining defintions in Swagger docs
我正在使用 Swagger 文档记录 API。我有几个端点共享一组通用的基本属性。我想使用 $ref 来引用该基本属性集,然后使用每个端点独有的附加属性来扩展这些属性。我想象它会像这样工作,但这是无效的:
"properties": {
"$ref": "#/definitions/baseProperties",
unique_thing": {
"type": "string"
},
"another_unique_thing": {
"type": "string"
}
}
确实,您在此处给出的示例无效,因为$ref
不能与同一对象中的其他属性共存。 $ref
是一个 JSON 引用,根据定义,将导致其他属性被忽略。
根据你的问题,我假设你正在寻找基本组合(而不是继承)。这可以使用 allOf
关键字实现。
因此,对于您提供的示例,您将得到如下内容:
{
"baseProperties": {
"type": "object",
"properties": {
...
}
},
"complexModel": {
"allOf": [
{
"$ref": "#/definitions/baseProperties"
},
{
"type": "object",
"properties": {
"unique_thing": {
"type": "string"
},
"another_unique_thing": {
"type": "string"
}
}
}
]
}
}
YAML 版本:
definitions:
baseProperties:
type: object
properties:
...
complexModel:
allOf:
- $ref: '#/definitions/baseProperties'
- type: object
properties:
unique_thing:
type: string
another_unique_thing:
type: string
您还可以查看 example in the spec。
我正在使用 Swagger 文档记录 API。我有几个端点共享一组通用的基本属性。我想使用 $ref 来引用该基本属性集,然后使用每个端点独有的附加属性来扩展这些属性。我想象它会像这样工作,但这是无效的:
"properties": {
"$ref": "#/definitions/baseProperties",
unique_thing": {
"type": "string"
},
"another_unique_thing": {
"type": "string"
}
}
确实,您在此处给出的示例无效,因为$ref
不能与同一对象中的其他属性共存。 $ref
是一个 JSON 引用,根据定义,将导致其他属性被忽略。
根据你的问题,我假设你正在寻找基本组合(而不是继承)。这可以使用 allOf
关键字实现。
因此,对于您提供的示例,您将得到如下内容:
{
"baseProperties": {
"type": "object",
"properties": {
...
}
},
"complexModel": {
"allOf": [
{
"$ref": "#/definitions/baseProperties"
},
{
"type": "object",
"properties": {
"unique_thing": {
"type": "string"
},
"another_unique_thing": {
"type": "string"
}
}
}
]
}
}
YAML 版本:
definitions:
baseProperties:
type: object
properties:
...
complexModel:
allOf:
- $ref: '#/definitions/baseProperties'
- type: object
properties:
unique_thing:
type: string
another_unique_thing:
type: string
您还可以查看 example in the spec。