在Swagger文档中合并定义

14

我正在使用Swagger文档记录API。 我有几个端点共享一组基本属性。 我想使用$ref引用该基本属性集,然后使用每个端点独有的其他属性来扩展这些属性。 我认为它应该像这样工作,但这是无效的:

"properties": {
    "$ref": "#/definitions/baseProperties",
    unique_thing": {
      "type": "string"
    },
    "another_unique_thing": {
      "type": "string"
    }
 }
1个回答

33

确实,你在这里提供的例子是无效的,因为$ref不能与同一对象中的其他属性共存。 $ref是JSON引用,并且根据定义,将导致忽略其他属性。

从你的问题中,我认为你正在寻找基本组合(而不是继承)。使用allOf关键字可以实现这一点。

因此,以你提供的例子为基础,你可以得到以下内容:

{
  "baseProperties": {
    "type": "object",
    "properties": {
        ...
    }
  },
  "complexModel": {
    "allOf": [
      {
        "$ref": "#/definitions/baseProperties"
      },
      {
        "type": "object",
        "properties": {
          "unique_thing": {
            "type": "string"
          },
          "another_unique_thing": {
            "type": "string"
          }
        }
      }
    ]
  }
}

YAML 版本:

definitions:
  baseProperties:
    type: object
    properties:
       ...
  complexModel:
    allOf:
      - $ref: '#/definitions/baseProperties'
      - type: object
        properties:
          unique_thing:
            type: string
          another_unique_thing:
            type: string

你还可以查看规范中的示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接