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

如何在Swagger响应中通过DTO设置数组类型返回值

配置Swagger响应为DTO数组的正确方式

我懂你想要的效果——让Swagger文档里的接口响应显示为CreateCatDto的数组,而且不想用直接指定type: CreateCatDto的方式,而是通过schema字段来配置对吧?你之前尝试的写法有个小问题,我来给你调整一下:

首先先确认你的CreateCatDto代码(方便上下文参考):

// some-dto.ts
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty() name: string;
  @ApiProperty() age: number;
  @ApiProperty() breed: string;
}

方法1:直接使用schema配置数组响应

这是最贴近你想要的写法,只需要修正schema里的结构:

import { ApiOkResponse } from '@nestjs/swagger';
import { CreateCatDto } from './some-dto';

// 在你的控制器方法上添加这个装饰器
@ApiOkResponse({
  description: '成功返回猫的列表',
  schema: {
    type: 'array', // 声明响应是数组类型
    items: { $ref: '#/components/schemas/CreateCatDto' } // 引用Swagger自动生成的DTO schema
  }
})

方法2:用NestJS Swagger工具函数更规范地配置

如果你不想硬写$ref的路径,可以用官方提供的工具函数,避免路径写错:

import { ApiOkResponse, ApiExtraModels, getSchemaPath } from '@nestjs/swagger';
import { CreateCatDto } from './some-dto';

// 先把DTO注册为Swagger的额外模型
@ApiExtraModels(CreateCatDto)
@ApiOkResponse({
  description: '成功返回猫的列表',
  schema: {
    type: 'array',
    items: { $ref: getSchemaPath(CreateCatDto) } // 自动获取DTO的schema路径
  }
})

为什么你的原写法不对?

你之前写的properties: { obj: { type: CreateCatDto } }是用来定义对象里的属性的,而数组类型需要用items字段来指定每个元素的类型,所以调整成上面的写法就能正确显示数组响应啦。

内容的提问来源于stack exchange,提问作者har17bar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 21:42:39