在我的 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.
而对特定库的请求应返回上述所有内容,包括额外的参数 books:
所以一个 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 模型中?
正如评论部分提到的,这可能是重复的另一个问题,但值得在这个特定示例的上下文中重复答案。解决方案是使用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 可以正确地可视化这一点。当我将操作响应定义为ExtendedLibrary
Swagger UI 显示了这个示例:
{
"library_id": "string",
"display_name": "string",
"href": "string",
"books": [
{
"title": "string",
"author": "string"
}
]
}
此外,Swagger Codegen 做了正确的事情。至少在生成 Java 客户端时,它会创建一个ExtendedLibrary
正确扩展的类BaseLibrary
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)