当前位置: 首页 > news >正文

Nest 中使用Swagger自动化API文档生成

1. 基础概念与使用

OpenAPI 规范是一种与语言无关的定义格式,用于描述 RESTful APIs。Nest 提供了一个专门的模块,通过装饰器,可以自动生成符合 OpenAPI 规范的文档。

首先,我们需要安装生成文档的必要依赖:

$ npm install --save @nestjs/swagger

在安装完成之后,打开 main.ts 文件,使用 SwaggerModule 类初始化 Swagger。

import { NestFactory } from '@nestjs/core';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';async function bootstrap() {const app = await NestFactory.create(AppModule);const config = new DocumentBuilder().setTitle('Cats example').setDescription('The cats API description').setVersion('1.0').addTag('cats').build();const document = SwaggerModule.createDocument(app, config);SwaggerModule.setup('api', app, document);await app.listen(3000);
}
bootstrap();
  • DocumentBuilder 帮助我们构建一个符合 OpenAPI 规范的基本文档。通过其方法可以设置标题、描述、版本等属性。

  • SwaggerModule.createDocument() 方法生成包含所有 HTTP 路由定义的完整文档。

  • SwaggerModule.setup() 用于将 Swagger UI 安装在指定的路径上,接收的参数包括路径、应用实例和生成的文档对象。

运行以下命令启动 HTTP 服务器:

$ npm run start

在应用运行时,打开浏览器并访问 http://localhost:3000/api 查看 Swagger UI。

2. Swagger JSON 文件生成

你还可以生成并下载 Swagger JSON 文件。默认情况下,它位于  http://localhost:3000/api-json,你还可以通过SwaggerModule.setup() 方法自定义路径,如下所示:

SwaggerModule.setup('swagger', app, document, {jsonDocumentUrl: 'swagger/json',
});

该设置将 Swagger JSON 文件暴露在 http://localhost:3000/swagger/json。

在 NestJS 项目中,@nestjs/swagger 提供了多种注解用于配置 API 文档。结合你提供的示例项目 (NestJS Swagger 示例项目),我们可以进一步扩展 Swagger 注解的配置使用。

以下是一些常见的 Swagger 注解配置用法及代码示例,以便更好地完善自动化 API 文档生成功能。

3. Swagger 注解使用及代码示例

3.1. @ApiTags() - 为控制器打标签

用于给控制器或特定的路由分配标签,这些标签会显示在 Swagger UI 中的侧边栏。

import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';@ApiTags('cats')
@Controller('cats')
export class CatsController {@Get()findAll() {return 'This action returns all cats';}
}

3.2. @ApiOperation() - 路由的描述信息

可以给每个操作添加简短的描述,展示在 Swagger UI 中。

import { Controller, Get } from '@nestjs/common';
import { ApiOperation } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get()@ApiOperation({ summary: 'Get all cats' })findAll() {return 'This action returns all cats';}
}

3.3. @ApiResponse() - 定义响应状态及描述

用来为操作指定响应状态码及其描述。

import { Controller, Get } from '@nestjs/common';
import { ApiResponse } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get()@ApiResponse({ status: 200, description: 'Successful retrieval of cat list.' })@ApiResponse({ status: 404, description: 'Cats not found.' })findAll() {return 'This action returns all cats';}
}

3.4. @ApiParam() - 定义 URL 路径参数

用于定义 API 路径参数的相关信息。

import { Controller, Get, Param } from '@nestjs/common';
import { ApiParam } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get(':id')@ApiParam({ name: 'id', required: true, description: 'ID of the cat to retrieve' })findOne(@Param('id') id: string) {return `This action returns a cat with id: ${id}`;}
}

3.5. @ApiQuery() - 定义查询参数

用于描述请求中的查询参数及其属性。

import { Controller, Get, Query } from '@nestjs/common';
import { ApiQuery } from '@nestjs/swagger';@Controller('cats')
export class CatsController {@Get()@ApiQuery({ name: 'age', required: false, description: 'Filter cats by age' })findAll(@Query('age') age: number) {return `This action returns all cats with age: ${age}`;}
}

3.6. @ApiBody() - 定义请求体

用来描述 POST、PUT 等请求中的请求体内容。

import { Controller, Post, Body } from '@nestjs/common';
import { ApiBody } from '@nestjs/swagger';class CreateCatDto {name: string;age: number;breed: string;
}@Controller('cats')
export class CatsController {@Post()@ApiBody({description: 'Details of the cat to create',schema: {type: 'object',properties: {name: { type: 'string' },age: { type: 'integer' },breed: { type: 'string' }}}})create(@Body() createCatDto: CreateCatDto) {return `This action adds a new cat with name: ${createCatDto.name}`;}
}

3.7. @ApiProperty() - 定义 DTO 中的属性

通常用于描述 DTO 类的属性,帮助生成 API 请求和响应的定义。

import { ApiProperty } from '@nestjs/swagger';export class CreateCatDto {@ApiProperty({ description: 'The name of the cat' })name: string;@ApiProperty({ description: 'The age of the cat', example: 3 })age: number;@ApiProperty({ description: 'The breed of the cat' })breed: string;
}

3.8. @ApiBearerAuth() - 为 API 添加认证信息

用于指定操作需要认证的接口。

import { Controller, Get, UseGuards } from '@nestjs/common';
import { ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';@Controller('cats')
export class CatsController {@Get('protected')@UseGuards(AuthGuard('jwt'))@ApiBearerAuth()getProtectedData() {return 'This action returns protected data';}
}

3.9. @ApiExtraModels() 和 @ApiExcludeEndpoint() 

@ApiExtraModels() 可用于引用额外的模型,而 @ApiExcludeEndpoint() 可用于在 Swagger 中隐藏某些路由。

import { ApiExtraModels, ApiExcludeEndpoint } from '@nestjs/swagger';
import { Controller, Get } from '@nestjs/common';class CatDetails {name: string;age: number;
}@ApiExtraModels(CatDetails)
@Controller('cats')
export class CatsController {@Get('hidden')@ApiExcludeEndpoint()getHidden() {return 'This route is hidden from Swagger';}
}

4. 补充资料

  • Nestjs 集成第三方模块示例:https://docs.nestjs.com/techniques/caching#different-stores

  • Nestjs 继承 ORM:https://docs.nestjs.com/techniques/database

  • Nestjs 定时任务:https://docs.nestjs.com/techniques/task-scheduling

  • 集成 Kafka:https://docs.nestjs.com/microservices/kafka

  • 接口文档生成:https://docs.nestjs.com/openapi/introduction

  • 身份鉴权:https://docs.nestjs.com/security/authentication

  • 访问控制:https://docs.nestjs.com/security/rate-limiting

  • 官方 Devtools:https://docs.nestjs.com/devtools/overview​​​​​​​

http://www.dtcms.com/a/430957.html

相关文章:

  • 融合:迈向 “一台计算机” 的终极架构
  • ai手诊面诊抖音快手微信小程序看广告流量主开源
  • 网页设计制作手机网站网站做了301怎么查看跳转前网站
  • 安卓基础组件018--第三方Image库
  • 25.60 秒计时器,仅使用 HTML 和 CSS | CSS SVG 动画
  • 网站推广工作计划乌市网络营销公司
  • 微信小程序入门学习教程,从入门到精通,微信小程序常用API(下)——知识点详解 + 案例实战(5)
  • iptables vs nftables
  • 5.网站滚动动画效果 | CSS 与 JavaScript
  • 国家精品课程建设工作网站优设网logo设计
  • 注册网站费用互动网页设计是什么
  • 千年游戏智慧:传承的密码
  • 云平台网站建设网站建设销售专业话术
  • 嵌入式八股文-ARM
  • 《CRM性能突围:从4秒卡顿到毫秒级响 应的全链路实战拆解》
  • 函数性质:命题中的抽象问题与具体构造
  • LDPC 码的密度进化(二)
  • python读取文件的常用操作
  • 怎样通过阿里巴巴网站开发客户上海搜索seo
  • Python基础训练
  • OSPF Full 状态 概念及题目
  • algorithm: DFS 示例及pseduocode及visited 5/999
  • 机器学习——聚类kmeans算法详解
  • 在Ubuntu如何安装Python3.9(Ubuntu 20.04)
  • Linux任务切换统计和局部描述符表设置以及加载函数的实现
  • ICT 数字测试原理 3 --SAFETYGUARD 文件
  • 网站改版用新空间好吗北京市保障房建设投资中心网站首页
  • 中职计算机网站建设教学计划医院网站建设策划书
  • [NOIP 2015 提高组] 神奇的幻方 Java
  • 基于单片机的黑板粉尘检测清除装置(论文+源码)