Swagger:如何让属性引用 OpenAPI 2.0 中的模型(即嵌套模型)? [英] Swagger: How to have a property reference a model in OpenAPI 2.0 (i.e. nest the models)?

查看:17
本文介绍了Swagger:如何让属性引用 OpenAPI 2.0 中的模型(即嵌套模型)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having a hard time trying to figure out how I can nest models in OpenAPI 2.0.

目前我有:

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

OtherModel:
  properties:
    otherProp:
      type: string   

我尝试了很多其他方法:

I have tried many other ways:

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

上述方法似乎都不起作用.

None of the above seem to work.

但是,使用数组就可以了:

However, with arrays works just fine:

prop3:
  type: array
  items:
    $ref: OtherModel

推荐答案

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

The correct way to model it in OpenAPI 2.0 would be:

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:

If you use OpenAPI 3.0, models live in components/schemas instead of 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 添加到您的对象架构中,因为无法推断出 类型来自其他关键字.

Remember to add type: object to your object schemas because the type is not inferred from other keywords.

这篇关于Swagger:如何让属性引用 OpenAPI 2.0 中的模型(即嵌套模型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆