2014-11-08 100 views
6

假设我有一个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" 
      } 
     } 
    }, 
    ... 
} 
+0

在我进入答案之前,你为什么要引用一个* primitive *定义?什么让你保存在书面上? – Ron 2014-11-08 08:16:24

+0

我想我认为任何人阅读REST文档以查看“链接”模型会更清楚。 – roberkules 2014-11-08 08:18:38

+0

如果我需要改变UserType.id的类型,我不需要更新所有的引用。 – roberkules 2014-11-08 08:24:36

回答

6

在扬鞭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"以更好地记录该目的。

+1

是的,这是目前的方式。遗憾的是,它丢失了一些可能对基于模式生成数据库非常有用的数据。 – 2015-01-08 13:26:52

+0

没有错。这是一个API文档工具,而不是应用程序/数据库之一。从API表示到数据库表示的投影往往不是根本错误。 – Ron 2015-01-08 13:34:05

+0

这是否仍然有效? – Yerken 2016-12-20 10:36:33

相关问题