16

我很难弄清楚如何在 OpenAPI 2.0 中嵌套模型。

目前我有:

SomeModel:
 properties:
   prop1:
     type: string
   prop2:
     type: integer
   prop3:
     type:
       $ref: OtherModel

OtherModel:
  properties:
    otherProp:
      type: string   

我尝试了许多其他方法:

prop3:
  $ref: OtherModel
# or
prop3:
  schema:
    $ref: OtherModel
# or
prop3:
  type:
    schema:
      $ref: OtherModel

以上似乎都不起作用。

但是,使用数组可以正常工作:

prop3:
  type: array
  items:
    $ref: OtherModel
4

2 回答 2

36

在 OpenAPI 2.0 中对其建模的正确方法是:

swagger: '2.0'
...

definitions:
  SomeModel:
    type: object
    properties:
      prop1:
        type: string
      prop2:
        type: integer
      prop3:
        $ref: '#/definitions/OtherModel'   # <-----

  OtherModel:
    type: object
    properties:
      otherProp:
        type: string

如果您使用 OpenAPI 3.0,模型将components/schemas代替definitions

openapi: 3.0.1
...

components:
  schemas:
    SomeModel:
      type: object
      properties:
        prop1:
          type: string
        prop2:
          type: integer
        prop3:
          $ref: '#/components/schemas/OtherModel'   # <-----

    OtherModel:
      type: object
      properties:
        otherProp:
          type: string

请记住添加type: object到您的对象模式,因为类型不是从其他关键字推断出来的。

于 2014-10-16T17:35:10.210 回答
2

这是另一个有效的技巧。此解决方案适用于 OpenAPI 3 – OpenAPI 规范的最新版本,作为回答此问题的重点。

方法如下

说,我有一个User带有State枚举的模型。我在不同的模式中定义了State枚举,然后在User模式中引用了它。

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
        first_name:
          type: string
        last_name:
          type: string
        password:
          type: string
          format: password
        state:
          $ref: '#/components/schemas/State'
    State:
      type: string
      description: List of States
      enum:
        - State 1
        - State 2
        - State 3
        - State 4
        - State 5

请注意,枚举在这里表示为数组,如果您想将它们表示为哈希,请查看Representing enum property in hash中的此解决方案。

就这样。

我希望这有帮助

于 2020-03-25T07:30:28.400 回答