在OpenAPI 3中,如何最好地描述包含真实数据类型的泛型响应类型。
简化示例:
ApiResponse:
data: object
error: string
但是/users端点应该提供:
ApiResponse<List<User>>
所以这基本上就是:
ApiResponse:
data: List<User>
error: string
目前看起来这是不可能的,但我只是想确认一下。我想现在最好的方法是对每个调用进行命名响应,并使用allOf引用ApiResponse并实现数据:特定值。
发布于 2018-08-06 09:59:49
我花了很多时间寻找泛型类型,但是没有办法在OpenAPI3中定义泛型类型。最简单的方法是同时使用allOf和$ref。假设有如下列表模式:
List:
type: object
properties:
page_number:
type: integer
page_count:
type: integer
书的模式是
Book:
type: object
properties:
title:
type: string
summary:
type: string
要返回列表,路径为:
/api/v1/books:
get:
responses:
default:
description: description text
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/List'
- type: object
properties:
items:
type: array
items:
$ref: '#/components/schemas/Book'
这个结果是
{
"page_number": 1,
"page_count": 10,
"items": [{
"title": "title",
"description": ""
},
... ]
}
实际上,这是一份书单。如您所见,您可以同时将列表的主要属性添加到结果和列表项类型中。您也可以对其他人重复此模式:
/api/v1/authors:
get:
responses:
default:
description: description text
content:
application/json:
schema:
allOf:
- $ref: '#/components/schemas/List'
- type: object
properties:
items:
type: array
items:
$ref: '#/components/schemas/Author'
发布于 2019-01-15 15:26:35
您可以使用带有additionalProperties
的类型object
和true值来获取自由形式的对象。
https://stackoverflow.com/questions/51499445
复制