返回

用nestjs 编写后端接口 使用swagger作为接口文档

前端

在 NestJS 中使用 Swagger 来简化后端开发

简介

在当今快节奏的软件开发环境中,API(应用程序编程接口)已成为不可或缺的一部分。API 允许不同的系统或应用程序通过预定义的接口进行无缝通信和交互。为了确保 API 的易用性和可理解性,API 文档至关重要。

Swagger:API 文档的神器

Swagger 是一个广受认可的框架,用于生成和维护 API 文档。它为 API 提供了一种统一的文档格式,使开发人员能够轻松查看和测试 API。通过使用 Swagger,您可以显著提高 API 的可访问性和可发现性。

安装 NestJS 和 Swagger

要将 Swagger 集成到 NestJS 应用程序中,我们需要安装以下依赖项:

npm install --save @nestjs/core @nestjs/platform-express swagger-ui-express

配置 NestJS 应用程序

在我们的 NestJS 应用程序中,我们必须配置 Swagger。让我们打开 main.ts 文件并添加以下代码:

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Swagger 配置
  const config = new DocumentBuilder()
    .setTitle('NestJS API')
    .setDescription('NestJS API description')
    .setVersion('1.0')
    .addTag('api')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  // 全局验证管道
  app.useGlobalPipes(new ValidationPipe());

  await app.listen(3000);
}
bootstrap();

定义路由

在 NestJS 中,路由由控制器定义。让我们创建一个名为 PostController 的简单控制器,以展示如何使用 Swagger 定义路由:

import { Controller, Get, Post, Body } from '@nestjs/common';
import { PostsService } from './posts.service';
import { CreatePostDto } from './dto/create-post.dto';

@Controller('posts')
export class PostsController {
  constructor(private readonly postsService: PostsService) {}

  @Post()
  create(@Body() createPostDto: CreatePostDto) {
    return this.postsService.create(createPostDto);
  }

  @Get()
  findAll() {
    return this.postsService.findAll();
  }
}

使用 Swagger UI 查看文档

配置 Swagger 并定义路由后,我们可以使用 Swagger UI 查看和测试 API 文档。在浏览器中访问 http://localhost:3000/api,即可看到 Swagger UI。

在 Swagger UI 中,您可以找到 API 的完整文档,包括接口路径、参数、响应和其他相关信息。此外,您还可以使用 Swagger UI 直接在浏览器中测试 API,发送请求并查看响应。

结论

通过利用 Swagger 在 NestJS 中创建 API 文档,您可以显著提升 API 的易用性和可发现性。通过使用 Swagger,开发人员可以轻松地查看和测试 API,从而减少开发时间并提高整体生产力。

常见问题解答

1. Swagger 的优点是什么?

  • 提供统一的 API 文档格式,提高 API 的易用性和可发现性
  • 允许开发人员轻松查看和测试 API
  • 减少开发时间并提高生产力

2. 如何在 NestJS 中安装 Swagger?

使用以下命令安装依赖项:

npm install --save @nestjs/core @nestjs/platform-express swagger-ui-express

3. 如何配置 Swagger 在 NestJS 中?

main.ts 文件中添加以下配置代码:

// Swagger 配置
const config = new DocumentBuilder()
  .setTitle('NestJS API')
  .setDescription('NestJS API description')
  .setVersion('1.0')
  .addTag('api')
  .build();
const document = SwaggerModule.createDocument(app, config);
SwaggerModule.setup('api', app, document);

4. 如何定义使用 Swagger 的路由?

在控制器类中使用 @Post()@Get() 等装饰器来定义路由。

5. 如何使用 Swagger UI 查看文档?

在浏览器中访问 http://localhost:3000/api,即可访问 Swagger UI。