类型与参数
SwaggerModule 会在路由处理器中查找所有 @Body()、@Query()、@Param() 和 @Headers() 装饰器,以生成 API 文档。它还会利用反射创建相应的模型定义。考虑以下代码:
@Post()
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}要显式设置请求体定义,请使用 @ApiBody() 装饰器(从 @nestjs/swagger 包导入)。
基于 CreateCatDto,Swagger UI 会显示如下模型定义:

该定义是空的,尽管这个类声明了几个属性。要让类的属性对 SwaggerModule 可见,可以用 @ApiProperty() 装饰器标注它们,或者使用 CLI 插件,后者会自动完成这件事:
import { ApiProperty } from '@nestjs/swagger';
export class CreateCatDto {
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}与其手动逐个标注属性,不如考虑使用 Swagger 插件,它会替你添加这些标注。
打开浏览器,确认生成的 CreateCatDto 模型:

@ApiProperty() 装饰器还让你可以设置各种 Schema 对象属性:
@ApiProperty({
description: 'The age of a cat',
minimum: 1,
default: 1,
})
age: number;与其显式写出 {{"@ApiProperty({ required: false })"}},你可以使用 @ApiPropertyOptional() 这个简写装饰器。
要显式设置属性的类型,请使用 type 键:
@ApiProperty({
type: Number,
})
age: number;数组
当属性是数组时,你必须手动指明数组类型,如下所示:
@ApiProperty({ type: [String] })
names: string[];可以考虑使用 Swagger 插件,它会自动识别数组。
要么把类型作为数组的第一个元素传入(如上所示),要么把 isArray 属性设为 true。
循环依赖
当类之间存在循环依赖时,请用惰性函数向 SwaggerModule 提供类型信息:
@ApiProperty({ type: () => Node })
node: Node;可以考虑使用 Swagger 插件,它会自动识别循环依赖。
泛型与接口
TypeScript 不保存关于泛型或接口的元数据,因此当你在数据传输对象(DTO)中使用它们时,SwaggerModule 可能无法在运行时正确生成模型定义。例如,Swagger 模块无法正确解析下面的代码:
createBulk(@Body() usersDto: CreateUserDto[])要绕过这一限制,请显式设置类型:
@ApiBody({ type: [CreateUserDto] })
createBulk(@Body() usersDto: CreateUserDto[])枚举
要标识一个 enum,请把 @ApiProperty() 的 enum 属性设为值数组:
@ApiProperty({ enum: ['Admin', 'Moderator', 'User']})
role: UserRole;或者,按如下方式定义一个真正的 TypeScript 枚举:
export enum UserRole {
Admin = 'Admin',
Moderator = 'Moderator',
User = 'User',
}之后你就可以把枚举直接用于 @Query() 参数装饰器,并配合 @ApiQuery() 装饰器:
@ApiQuery({ name: 'role', enum: UserRole })
async filterByRole(@Query('role') role: UserRole = UserRole.User) {}
把 isArray 设为 true 后,enum 的值就可以在 多选 中选择:

枚举 schema
默认情况下,enum 属性会给 parameter 添加一个原始的枚举定义:
- breed:
type: 'string'
enum:
- Persian
- Tabby
- Siamese这份规范在大多数情况下都适用。不过,如果你使用某个工具,把这份规范作为 输入 并生成 客户端 代码,那么生成的代码中可能出现重复的 enums。考虑下面的代码片段:
// 生成的客户端代码
export class CatDetail {
breed: CatDetailEnum;
}
export class CatInformation {
breed: CatInformationEnum;
}
export enum CatDetailEnum {
Persian = 'Persian',
Tabby = 'Tabby',
Siamese = 'Siamese',
}
export enum CatInformationEnum {
Persian = 'Persian',
Tabby = 'Tabby',
Siamese = 'Siamese',
}上面的代码片段是用一个名为 NSwag 的工具生成的。
结果里包含两个完全相同的 enums。要解决这个问题,请在装饰器中随 enum 属性一起传入 enumName:
export class CatDetail {
@ApiProperty({ enum: CatBreed, enumName: 'CatBreed' })
breed: CatBreed;
}enumName 属性会让 @nestjs/swagger 把 CatBreed 变成它自己的 schema,从而使 CatBreed 枚举可复用。规范看起来如下:
CatDetail:
type: 'object'
properties:
...
- breed:
schema:
$ref: '#/components/schemas/CatBreed'
CatBreed:
type: string
enum:
- Persian
- Tabby
- Siamese@ApiQuery() 和 @ApiParam() 装饰器也接受与 enum 并列的 enumName。
属性值示例
要为属性设置单个示例,请使用 example 键:
@ApiProperty({
example: 'persian',
})
breed: string;要提供多个示例,请使用 examples 键,并传入一个像下面这样结构的对象:
@ApiProperty({
examples: {
Persian: { value: 'persian' },
Tabby: { value: 'tabby' },
Siamese: { value: 'siamese' },
'Scottish Fold': { value: 'scottish_fold' },
},
})
breed: string;原始定义
某些情况下,例如深层嵌套的数组或矩阵,你可能需要手动定义类型:
@ApiProperty({
type: 'array',
items: {
type: 'array',
items: {
type: 'number',
},
},
})
coords: number[][];你也可以指定原始的对象 schema:
@ApiProperty({
type: 'object',
properties: {
name: {
type: 'string',
example: 'Error'
},
status: {
type: 'number',
example: 400
}
},
required: ['name', 'status']
})
rawDefinition: Record<string, any>;要在控制器类中手动定义输入/输出内容,请使用 schema 属性:
@ApiBody({
schema: {
type: 'array',
items: {
type: 'array',
items: {
type: 'number',
},
},
},
})
async create(@Body() coords: number[][]) {}额外模型
要定义控制器没有直接引用、但 Swagger 模块应当检查的额外模型,请使用 @ApiExtraModels() 装饰器:
@ApiExtraModels(ExtraModel)
export class CreateCatDto {}对于某个具体的模型类,@ApiExtraModels() 只需使用一次。
或者,把一个带有 extraModels 属性的选项对象传给 SwaggerModule.createDocument() 方法:
const documentFactory = () =>
SwaggerModule.createDocument(app, options, {
extraModels: [ExtraModel],
});要获得指向你模型的引用($ref),请使用 getSchemaPath(ExtraModel) 函数:
'application/vnd.api+json': {
schema: { $ref: getSchemaPath(ExtraModel) },
},oneOf, anyOf, allOf
要组合 schema,请使用 oneOf、anyOf 或 allOf 关键字(参见 Swagger 文档中的 oneOf, anyOf, allOf, not):
@ApiProperty({
oneOf: [
{ $ref: getSchemaPath(Cat) },
{ $ref: getSchemaPath(Dog) },
],
})
pet: Cat | Dog;要定义多态数组(即成员跨越多个 schema 的数组),请用原始定义(见上文)手动定义类型:
type Pet = Cat | Dog;
@ApiProperty({
type: 'array',
items: {
oneOf: [
{ $ref: getSchemaPath(Cat) },
{ $ref: getSchemaPath(Dog) },
],
},
})
pets: Pet[];getSchemaPath() 函数从 @nestjs/swagger 导入。
Cat 和 Dog 都必须用 @ApiExtraModels() 装饰器(在类级别)定义为额外模型。
schema 名称与描述
生成的 schema 名称基于原始模型类的名称(例如 CreateCatDto 模型会生成 CreateCatDto schema)。要更改 schema 名称,请使用 @ApiSchema() 装饰器:
@ApiSchema({ name: 'CreateCatRequest' })
class CreateCatDto {}上面的模型会被转换为 CreateCatRequest schema。
默认情况下,生成的 schema 没有描述。要添加描述,请使用 description 属性:
@ApiSchema({ description: 'Description of the CreateCatDto schema' })
class CreateCatDto {}随后描述会被包含进 schema:
schemas:
CreateCatDto:
type: object
description: Description of the CreateCatDto schema@ApiSchema() 还接受作用于整个 schema 的关键字(在 @nestjs/swagger 12.1.3 及更高版本中):title、deprecated、example、examples、externalDocs、xml、discriminator、readOnly、writeOnly、nullable、additionalProperties、patternProperties、minProperties 和 maxProperties。它们会被原样复制进生成的 schema。例如,要把某个模型标记为已废弃,并声明它除了自身声明的属性之外不接受任何属性:
@ApiSchema({ deprecated: true, additionalProperties: false })
class LegacyCatDto {
@ApiProperty()
name: string;
}于是生成的 schema 会同时带上这两个关键字:
schemas:
LegacyCatDto:
type: object
properties:
name:
type: string
deprecated: true
additionalProperties: false
required:
- name