在我的API,我想有一个简单的模型为我的收藏和一个更详细的模型为我的个人资源。例如:
对/库
的GET请求应该返回
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.
而对特定库的请求应返回上述所有内容,包括额外的参数书籍:
因此,对库/{library_id}
的GET请求应该返回:
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模型中?
如评论部分所述,这可能是另一个问题的重复,但值得在这个特定示例的上下文中重复答案。解决方案是在ExtendedLibrary
的定义中使用allOf
属性:
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"
根据我的经验,SwaggerUI正确地可视化了这一点。当我将操作响应定义为ExtendedLibrary
Swagger时UI显示了这个示例:
{
"library_id": "string",
"display_name": "string",
"href": "string",
"books": [
{
"title": "string",
"author": "string"
}
]
}
此外,Swagger Codesen做了正确的事情。至少在生成Java客户端时,它会创建一个正确扩展BaseLibrary
的ExtendedLibrary
类。