You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过swagger-jsdoc在Swagger响应体中添加外层data键

用swagger-jsdoc定义带外层"data"键的响应体

当然可以实现,核心是在Swagger schema里定义一个包裹对象,把数组/单个条目放在data字段下,而不是直接用数组作为响应的顶层结构。以下是具体实现方式:

1. 定义通用的包裹Schema

先在组件中定义可复用的DataWrapper(支持数组)或SingleDataWrapper(支持单个条目),或者一个兼容两种情况的灵活版本:

数组响应的包裹Schema

/**
 * @swagger
 * components:
 *   schemas:
 *     # 单个条目的基础Schema
 *     Item:
 *       type: object
 *       properties:
 *         id:
 *           type: integer
 *           description: 条目ID
 *         name:
 *           type: string
 *           description: 条目名称
 *     # 包裹数组的Data结构
 *     ListDataWrapper:
 *       type: object
 *       properties:
 *         data:
 *           type: array
 *           items:
 *             $ref: '#/components/schemas/Item'
 */

单个条目响应的包裹Schema

如果接口返回单个条目,可单独定义:

/**
 * @swagger
 * components:
 *   schemas:
 *     SingleDataWrapper:
 *       type: object
 *       properties:
 *         data:
 *           $ref: '#/components/schemas/Item'
 */

兼容数组/单个条目的灵活版本

如果部分接口可能返回两种格式,用oneOf实现:

/**
 * @swagger
 * components:
 *   schemas:
 *     FlexibleDataWrapper:
 *       type: object
 *       properties:
 *         data:
 *           oneOf:
 *             - type: array
 *               items:
 *                 $ref: '#/components/schemas/Item'
 *             - $ref: '#/components/schemas/Item'
 */

2. 在接口文档中引用包裹Schema

在接口的responses里直接引用上述定义好的包裹Schema,替代原来的数组结构:

数组响应示例

/**
 * @swagger
 * /api/items:
 *   get:
 *     summary: 获取条目列表
 *     responses:
 *       200:
 *         description: 成功返回条目列表
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/ListDataWrapper'
 */

单个条目响应示例

/**
 * @swagger
 * /api/items/{id}:
 *   get:
 *     summary: 获取单个条目
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 成功返回单个条目
 *         content:
 *           application/json:
 *             schema:
 *               $ref: '#/components/schemas/SingleDataWrapper'
 */

这样配置后,Swagger UI就会正确显示带外层data键的响应结构,比如:

{
  "data": [
    {
      "id": 1,
      "name": "示例条目"
    }
  ]
}

或者单个条目格式:

{
  "data": {
    "id": 1,
    "name": "示例条目"
  }
}

内容的提问来源于stack exchange,提问作者Leonardo B. M.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 16:24:32