首页 文章

结合Swagger文档中的定义

提问于
浏览
7

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

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

1 回答

  • 14

    实际上,您在此处提供的示例无效,因为 $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
    

    您还可以查看example in the spec .

相关问题