结合Swagger文档中的定义

Bai*_*ith 7 swagger swagger-ui

我正在使用Swagger文档记录API.我有几个端点共享一组共同的基本属性.我想使用$ ref引用该基本属性集,然后使用每个端点唯一的附加属性扩展这些属性.我想它会像这样工作,但这是无效的:

"properties": {
    "$ref": "#/definitions/baseProperties",
    unique_thing": {
      "type": "string"
    },
    "another_unique_thing": {
      "type": "string"
    }
 }
Run Code Online (Sandbox Code Playgroud)

Ron*_*Ron 16

实际上,您在此处提供的示例无效,因为$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"
          }
        }
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

YAML版本:

definitions:
  baseProperties:
    type: object
    properties:
       ...
  complexModel:
    allOf:
      - $ref: '#/definitions/baseProperties'
      - type: object
        properties:
          unique_thing:
            type: string
          another_unique_thing:
            type: string
Run Code Online (Sandbox Code Playgroud)

您还可以查看规范中示例.