OpenAPI 重用部分定义,而无需定义新的定义



>假设我在yaml OpenApi定义中有这个定义

definitions:
  User:
    description: "User"
    type: "object"
    properties:
      firstname:
        type: "string"
      lastname:
        type: "string"
      password:
        type: "string"
      email:
        type: "string"
      username:
        type: "string"

如果在参数规范中我需要定义的特定字段,如何在不定义另一个模型的情况下引用它们,如下所示?

definitions:
  UserLogin:
    description: "User"
    type: "object"
    properties:
      password:
        type: "string"
      email:
        type: "string"

在您的问题中,您正在使用definitions关键字,暗示您的问题是关于 OpenAPI v2 aka。斯瓦格。对于 OpenAPI v3,下面提供的定义应在相应的组件对象部分中定义。

为了实现这一点,您必须将组合与关键字一起使用 allOf .这里有一个很好的例子与您的问题有关。首先,您必须定义一个较小的对象,然后将其包含在较大对象的定义中,如下所示:

definitions:
  UserLogin:
    description: User Login
    type: object
    properties:
      password:
        type: string
      email:
        type: string
  User:
    allOf:
    - $ref: '#/definitions/UserLogin'
    - description: User
      type: object
      properties:
        firstname:
          type: string
        lastname:
          type: string
        username:
          type: string

值得注意的是:

  • 一些较轻的实现可能不支持allOf关键字。
  • 使用组合可能会增加或减少文档的可读性,具体取决于用于命名架构的单词的复杂性和选择。

最新更新