如何引用Swagger中另一个模型定义的ID
问题描述:
假设我有一个User和一个UserType模型。我想在用户模型中添加对UserType-ID的引用。 swagger文档仅显示如何引用另一个(整个)模型,而不仅仅涉及它的一个属性。如何引用Swagger中另一个模型定义的ID
所以我想知道它甚至有可能只引用另一个模型定义的属性。
"definitions": {
"User": {
"required": [
"username",
"typeId"
],
"properties": {
"id": {
"type": "integer",
"format": "int32"
},
"username": {
"type": "string"
},
"typeId": {
"$ref": "UserType.id" // ==> this doesn't work! and without
// the ".id" part it would include all
// the properties of UserType
}
}
},
"UserType": {
"required": [
"name"
],
"properties": {
"id": {
"type": "integer",
"format": "int32"
},
"name": {
"type": "string"
}
}
}
}
或者是根本不可能的,它应该永远只是:
"definitions": {
"User": {
...
"properties": {
"typeId": {
"type": "integer",
"format": "int32"
}
}
},
...
}
答
在扬鞭2.0,方案对象没有必要描述模型(不像在以前的版本中的模型对象)。例如,如果查看“body”参数,则会看到需要将Schema定义为类型,但该模式也可以表示基元和数组。
对于上面的问题(和评论),我建议使用以下结构:
"defintions": {
"User": {
"required": [
"username",
"typeId"
],
"properties": {
"id": {
"type": "integer",
"format": "int32"
},
"username": {
"type": "string"
},
"typeId": {
"$ref": "#/definitions/TypeId"
}
}
},
"UserType": {
"required": [
"name"
],
"properties": {
"id": {
"$ref": "#/definitions/TypeId"
},
"name": {
"type": "string"
}
}
},
"TypeId": {
"type": "integer",
"format": "int32"
}
}
的TYPEID现在外部化,并应时间来和你想改变它的定义,你可以在一个地方改变它。当然,您可能需要在字段和模型中添加额外的"description"
以更好地记录该目的。
在我进入答案之前,你为什么要引用一个* primitive *定义?什么让你保存在书面上? – Ron 2014-11-08 08:16:24
我想我认为任何人阅读REST文档以查看“链接”模型会更清楚。 – roberkules 2014-11-08 08:18:38
如果我需要改变UserType.id的类型,我不需要更新所有的引用。 – roberkules 2014-11-08 08:24:36