3

在我的 API 中,我想为我的收藏提供一个简单的模型,并为我的个人资源提供一个更精细的模型。例如:

一个 GET 请求/libraries应该返回

BaseLibrary:
    type: object
    properties:
        library_id:
          type: string
          description: The id of the library
        display_name:
          type: string
          description: Name of the library
        href:
          type: string
          description: The URI linking to this library.

而对特定库的请求应返回上述所有内容,包括额外的参数书:

所以一个 GET 请求libraries/{library_id}应该返回:

ExtendedLibrary:
    type: object
    properties:
        library_id:
          type: string
          description: The id of the library
        display_name:
          type: string
          description: Name of the library
        href:
          type: string
          description: The URI linking to this library.
        books:
          type: array
          description: The books in this library
          items:
            $ref: "#/definitions/books"

我非常希望不必定义“BaseLibrary”两次,并希望简单地建模一个附加的“ExtendedLibrary”,其中包含基础库的所有响应和附加的书籍属性。

我尝试了很多不同的东西,最接近成功的是以下定义:

definitions:
  BaseLibrary:
    type: object
    properties:
        library_id:
          type: string
          description: The id of the library.
        display_name:
          type: string
          description: Name of the library
        href:
          type: string
          description: The URI linking to this library.

  ExtendedLibrary:
    type: object
    properties:
      $ref: "#/definitions/BaseLibrary/properties"
      books:
        type: array
        description: The available books for this library.
        items:
          $ref: "#/definitions/Book"

然而,这给了我一个“额外的 JSON 参考属性将被忽略:书籍”警告,并且输出似乎忽略了这个额外的属性。有没有一种干净的方法来处理我的问题?还是我只需要将整个 BaseLibrary 模型复制粘贴到我的 ExtendedLibrary 模型中?

4

1 回答 1

2

如评论部分所述,这可能与另一个问题重复,但值得在此特定示例的上下文中重复答案。解决方案是使用allOf定义中的属性ExtendedLibrary

definitions:
  Book:
    type: object
    properties:
      title:
        type: string
      author:
        type: string

  BaseLibrary:
    type: object
    properties:
      library_id:
        type: string
        description: The id of the library
      display_name:
        type: string
        description: Name of the library
      href:
        type: string
        description: The URI linking to this library.

  ExtendedLibrary:
    type: object
    allOf:
      - $ref: '#/definitions/BaseLibrary'
      - properties:
          books:
            type: array
            description: The books in this library
            items:
              $ref: "#/definitions/Book"

根据我的经验,Swagger UI 正确地可视化了这一点。当我将操作响应定义为ExtendedLibrarySwagger UI 时显示此示例:

{
  "library_id": "string",
  "display_name": "string",
  "href": "string",
  "books": [
    {
      "title": "string",
      "author": "string"
    }
  ]
}

此外,Swagger Codegen 做了正确的事。至少在生成 Java 客户端时,它会创建一个ExtendedLibrary正确扩展的类BaseLibrary

于 2017-03-02T16:00:46.453 回答