操作
在 OpenAPI 术语中,路径(paths)是你的 API 暴露的端点(资源),例如 /users 或 /reports/summary。操作(operations)是用于操纵这些路径的 HTTP 方法,例如 GET、POST 或 DELETE。
标签
要把控制器挂到某个特定的标签上,请使用 @ApiTags(...tags) 装饰器:
@ApiTags('cats')
@Controller('cats')
export class CatsController {}OpenAPI 3.2 扩展了 Tag 对象,使标签可以组织成层级结构,并标注一个关于它们应如何呈现的提示。要声明这些关系,请用 DocumentBuilder 预先定义标签,并把 parent 和 kind 选项传给 addTag():
const config = new DocumentBuilder()
.setOpenAPIVersion('3.2.0')
.addTag('Animals', 'Everything about animals', undefined, { kind: 'nav' })
.addTag('Cats', 'Cat operations', undefined, { parent: 'Animals' })
.addTag('Dogs', 'Dog operations', undefined, { parent: 'Animals' })
.build();parent 选项按名称引用另一个标签。kind 选项是一个自由格式、机器可读的字符串,用来提示该标签应如何使用,常见取值有 nav、badge 或 audience。同一个选项对象还接受 summary,这是 OpenAPI 3.2 Tag 对象的另一个字段。
parent 和 kind 字段属于 OpenAPI 3.2 的 Tag 对象。你必须调用 setOpenAPIVersion('3.2.0')。否则生成的文档仍声明 openapi: 3.0.0,严格的校验器会拒绝这些字段。层级字段只能通过 DocumentBuilder.addTag() 定义。@ApiTags() 装饰器会忽略它们,并记录一条警告。
请求头
要定义请求中预期携带的自定义请求头,请使用 @ApiHeader():
@ApiHeader({
name: 'X-MyHeader',
description: 'Custom header',
})
@Controller('cats')
export class CatsController {}响应
要定义自定义的 HTTP 响应,请使用 @ApiResponse() 装饰器:
@Post()
@ApiResponse({ status: 201, description: 'The record has been successfully created.'})
@ApiResponse({ status: 403, description: 'Forbidden.'})
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}Nest 提供了一组建立在 @ApiResponse() 之上的简写 API 响应 装饰器,每个常见状态码对应一个。它们包括:
@ApiOkResponse()@ApiCreatedResponse()@ApiAcceptedResponse()@ApiNoContentResponse()@ApiMovedPermanentlyResponse()@ApiFoundResponse()@ApiBadRequestResponse()@ApiUnauthorizedResponse()@ApiNotFoundResponse()@ApiForbiddenResponse()@ApiMethodNotAllowedResponse()@ApiNotAcceptableResponse()@ApiRequestTimeoutResponse()@ApiConflictResponse()@ApiPreconditionFailedResponse()@ApiTooManyRequestsResponse()@ApiGoneResponse()@ApiPayloadTooLargeResponse()@ApiUnsupportedMediaTypeResponse()@ApiUnprocessableEntityResponse()@ApiInternalServerErrorResponse()@ApiNotImplementedResponse()@ApiBadGatewayResponse()@ApiServiceUnavailableResponse()@ApiGatewayTimeoutResponse()@ApiDefaultResponse()
@Post()
@ApiCreatedResponse({ description: 'The record has been successfully created.'})
@ApiForbiddenResponse({ description: 'Forbidden.'})
async create(@Body() createCatDto: CreateCatDto) {
this.catsService.create(createCatDto);
}要为请求指定返回模型,请创建一个类,并用 @ApiProperty() 装饰器标注它的所有属性:
export class Cat {
@ApiProperty()
id: number;
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}然后你就可以把 Cat 模型用于响应装饰器的 type 属性:
@ApiTags('cats')
@Controller('cats')
export class CatsController {
@Post()
@ApiCreatedResponse({
description: 'The record has been successfully created.',
type: Cat,
})
async create(@Body() createCatDto: CreateCatDto): Promise<Cat> {
return this.catsService.create(createCatDto);
}
}打开浏览器,确认生成的 Cat 模型:

你不必为每个端点或控制器分别定义响应,而可以用 DocumentBuilder 类为所有端点定义一个全局响应。对于那些应用中每个端点都可能返回的响应(例如 401 Unauthorized 或 500 Internal Server Error 这类错误),这很有用。
const config = new DocumentBuilder()
.addGlobalResponse({
status: 500,
description: 'Internal server error',
})
// 其他配置
.build();文件上传
要为某个特定方法记录文件上传,请把 @ApiBody() 装饰器与 @ApiConsumes() 一起使用。下面是一个使用文件上传技巧的完整示例:
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiBody({
description: 'List of cats',
type: FileUploadDto,
})
uploadFile(@UploadedFile() file: Express.Multer.File) {}其中 FileUploadDto 的定义如下:
class FileUploadDto {
@ApiProperty({ type: 'string', format: 'binary' })
file: any;
}要处理多文件上传,请按如下方式定义 FilesUploadDto:
class FilesUploadDto {
@ApiProperty({ type: 'array', items: { type: 'string', format: 'binary' } })
files: any[];
}扩展
要为操作添加扩展,请使用 @ApiExtension() 装饰器。扩展名必须以 x- 为前缀(否则装饰器会抛出错误)。
@ApiExtension('x-foo', { hello: 'world' })进阶:泛型 ApiResponse
借助原始定义,你可以为 Swagger UI 定义一个泛型 schema。假设你有下面的数据传输对象(DTO):
export class PaginatedDto<TData> {
@ApiProperty()
total: number;
@ApiProperty()
limit: number;
@ApiProperty()
offset: number;
results: TData[];
}我们跳过了对 results 的装饰,因为稍后会为它提供一个原始定义。现在,再定义另一个 DTO,例如 CatDto,如下所示:
export class CatDto {
@ApiProperty()
name: string;
@ApiProperty()
age: number;
@ApiProperty()
breed: string;
}做好这些之后,你就可以定义一个 PaginatedDto<CatDto> 响应:
@ApiOkResponse({
schema: {
allOf: [
{ $ref: getSchemaPath(PaginatedDto) },
{
properties: {
results: {
type: 'array',
items: { $ref: getSchemaPath(CatDto) },
},
},
},
],
},
})
async findAll(): Promise<PaginatedDto<CatDto>> {}在这个示例中,响应通过 allOf 把 PaginatedDto 与一个类型为 Array<CatDto> 的 results 属性组合在一起。
getSchemaPath()返回给定模型在 OpenAPI 文档中的 OpenAPI schema 路径。allOf是一个 OAS 3 关键字,涵盖与继承相关的多种用例。
最后,由于没有任何控制器直接引用 PaginatedDto,SwaggerModule 目前还无法生成对应的模型定义。这种情况下,你必须把它添加为一个额外模型。例如,在控制器级别使用 @ApiExtraModels() 装饰器:
@Controller('cats')
@ApiExtraModels(PaginatedDto)
export class CatsController {}如果你现在运行 Swagger,该端点生成的 swagger.json 会定义如下响应:
"responses": {
"200": {
"description": "",
"content": {
"application/json": {
"schema": {
"allOf": [
{
"$ref": "#/components/schemas/PaginatedDto"
},
{
"properties": {
"results": {
"type": "array",
"items": {
"$ref": "#/components/schemas/CatDto"
}
}
}
}
]
}
}
}
}
}为了让它可复用,请为 PaginatedDto 创建一个自定义装饰器:
export const ApiPaginatedResponse = <TModel extends Type<any>>(
model: TModel,
) => {
return applyDecorators(
ApiExtraModels(PaginatedDto, model),
ApiOkResponse({
schema: {
allOf: [
{ $ref: getSchemaPath(PaginatedDto) },
{
properties: {
results: {
type: 'array',
items: { $ref: getSchemaPath(model) },
},
},
},
],
},
}),
);
};Type<any> 接口和 applyDecorators() 函数从 @nestjs/common 包导入。
为确保 SwaggerModule 为该模型生成定义,该装饰器用 ApiExtraModels() 把它注册为额外模型,就像我们先前在控制器中为 PaginatedDto 所做的那样。
做好这些之后,你就可以在端点上使用自定义的 @ApiPaginatedResponse() 装饰器:
@ApiPaginatedResponse(CatDto)
async findAll(): Promise<PaginatedDto<CatDto>> {}对于客户端生成工具来说,这种做法会让 PaginatedDto<TModel> 应如何为该客户端生成变得有歧义。下面的代码片段是针对上面 GET / 端点的客户端生成结果示例:
// Angular
findAll(): Observable<{ total: number, limit: number, offset: number, results: CatDto[] }>这里的 返回类型 是有歧义的。要绕过这个问题,请在 ApiPaginatedResponse 中为 schema 添加一个 title 属性:
export const ApiPaginatedResponse = <TModel extends Type<any>>(
model: TModel,
) => {
return applyDecorators(
ApiOkResponse({
schema: {
title: `PaginatedResponseOf${model.name}`,
allOf: [
// ...
],
},
}),
);
};客户端生成器的结果现在变成了:
// Angular
findAll(): Observable<PaginatedResponseOfCatDto>