Creating an extendible model using Swagger/ OpenAPI

流过昼夜 提交于 2019-12-01 22:47:21
Dave Delay

As mentioned in the comments section, this may be a duplicate of another question, but it's worth repeating the answer in the context of this particular example. The solution is to use the allOf property in the definition of 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"

In my experience, Swagger UI visualizes this correctly. When I define an operation response to be ExtendedLibrary Swagger UI shows this example:

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

Also, Swagger Codegen does the right thing. At least when generating a Java client, it creates an ExtendedLibrary class that correctly extends BaseLibrary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!