在我的API中,我想为我的集合提供一个简单的模型,并为我的个人资源提供更精细的模型。例如:
/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.
虽然对特定库的请求应返回以上所有内容,包括额外的参数簿:
因此,请求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"
我非常希望不必两次定义"基本纤维",并且想简单模型一个附加的" 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参考属性将被忽略:书籍"警告,输出似乎忽略了此额外的属性。有没有干净的方法来解决我的问题?还是我只需要将整个基本图模型复制到我的扩展元模型中?
如评论部分所述,这可能是另一个问题的重复,但是在此特定示例的上下文中,值得重复答案。解决方案是在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"
根据我的经验,Swagger UI正确地可视化了这一点。当我将操作响应定义为ExtendedLibrary
Swagger UI时,请显示此示例:
{
"library_id": "string",
"display_name": "string",
"href": "string",
"books": [
{
"title": "string",
"author": "string"
}
]
}
此外,Swagger Codegen做正确的事情。至少在生成Java客户端时,它会创建一个ExtendedLibrary
类,该类正确扩展了BaseLibrary
。