Skip to main content

swagger

Swagger 是一種用於設計、建立、記錄和使用 REST API 的工具,可以幫助我們視覺化和測試我們的 endpoints。在 NestJS 中使用 Swagger 非常簡單且直觀。

以下是在 NestJS 中使用 Swagger 的基本步驟:

  1. 安裝必要的套件:

    使用 npm 或 yarn 安裝 @nestjs/swaggerswagger-ui-express 套件。

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

    yarn add @nestjs/swagger swagger-ui-express
  2. 引入 Swagger 模組:

    在你的應用程式的主模組(通常是 app.module.ts)中引入 Swagger 模組並設定。

    import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';

    //...
    const config = new DocumentBuilder()
    .setTitle('My API title')
    .setDescription('My API description')
    .setVersion('1.0')
    .build();
    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api', app, document);
    //...

    這裡,setTitlesetDescriptionsetVersion 分別設定了 Swagger 文檔的標題、描述和版本。createDocument 方法則是建立文檔,而 setup 方法則是設置 Swagger UI 的路徑(在這裡是 /api)。

  3. 使用裝飾器添加 API 資訊:

    在你的控制器和路由處理函數中使用 Swagger 提供的裝飾器來添加更多關於你的 API 的資訊。

    import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';

    @ApiTags('cats')
    @Controller('cats')
    export class CatsController {
    @Post()
    @ApiOperation({ summary: 'Create cat' })
    @ApiResponse({ status: 201, description: 'The cat has been successfully created.'})
    @ApiResponse({ status: 403, description: 'Forbidden.'})
    async create(@Body() createCatDto: CreateCatDto) {
    //...
    }

    //...
    }

    在上面的例子中,我們使用了 ApiTags 來為我們的控制器添加標籤,ApiOperation 來添加操作的簡短描述,以及 ApiResponse 來描述可能的回應。