OpenAPI 3.0通用数据类型 [英] OpenAPI 3.0 Generic Data types

查看:173
本文介绍了OpenAPI 3.0通用数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何最好地描述通用响应类型,其中包括OpenAPI 3中的实际数据类型.

How can I best describe a generic response type which includes the real data type in OpenAPI 3.

简化示例:

ApiResponse:
  data: object
  error: string

但是/users端点应该提供:

But the /users endpoint should give:

ApiResponse<List<User>>

所以基本上是:

ApiResponse:
  data: List<User>
  error: string

目前看来这是不可能的,但只是要确定一下. 我想现在最好的方法是为每个调用做出命名响应,并使用allOf引用ApiResponse和有效数据:特定值.

It looks like this is not possible at the moment, but just want to make sure. I guess the best way to do this now is to make named responses for every call and use allOf to refer to ApiResponse and implemenent data: specific value.

推荐答案

我花了很多时间搜索泛型类型,但是无法在OpenAPI3中定义泛型类型.最简单的方法是同时使用allOf和$ ref.假设有一个列表架构,如下所示:

I search for generic types much time, but there is no way to define a generic type in OpenAPI3. The simplest way is using allOf and $ref at the same time. Suppose there is a list schema as follow:

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": ""
        },
        ... ]
    }

实际上,这是一本书籍清单.如您所见,您可以将列表的主要属性同时添加到结果和列表项类型中.您也可以对其他人重复此模式:

Actually, this is a list of books. As you can see, you add main attributes of the list to the result and list item type at the same time. You can repeat this pattern for others too:

  /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'

这篇关于OpenAPI 3.0通用数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆