gpt4 book ai didi

swagger - 使用 Swagger/OpenAPI 创建可扩展模型

转载 作者:行者123 更新时间:2023-12-02 01:16:12 30 4
gpt4 key购买 nike

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

/libraries 上的 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.

虽然对特定图书馆的请求应该返回以上所有内容,包括额外的参数书:

因此对 libraries/{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 模型中?

最佳答案

如评论部分所述,这可能与 another question 重复,但值得在此特定示例的上下文中重复答案。解决方案是在 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 客户端时,它会创建一个正确扩展 BaseLibraryExtendedLibrary 类。

关于swagger - 使用 Swagger/OpenAPI 创建可扩展模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42496266/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com