结合 Swagger 文档中的定义 [英] Combining defintions in Swagger docs

查看:33
本文介绍了结合 Swagger 文档中的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm documenting an API with Swagger docs. I have several endpoints that share a common set of base properties. I'd like to use $ref to refer to that base set of properties and then extend those properties with additional properties that are unique to each endpoint. I imagined that it would work something like this, but this is invalid:

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

推荐答案

确实,您在此处给出的示例无效,因为 $ref 不能与同一对象中的其他属性共存.$ref 是一个 JSON 引用,根据定义,会导致其他属性被忽略.

Indeed, the example you give here is invalid because $ref can't co-exist with other properties in the same object. $ref is a JSON Reference, and by definition, will cause the other properties to be ignored.

根据您的问题,我假设您正在寻找基本组合(而不是继承).这可以使用 allOf 关键字来实现.

From your question, I assume you're looking for basic composition (rather than inheritance). This is achievable using the allOf keyword.

因此,使用您提供的示例,您会得到如下内容:

So, with the example you provided, you would have something like this:

{
  "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

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

这篇关于结合 Swagger 文档中的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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