2014-11-08 98 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

相關問題