Published on

NestJS에서 Swagger로 API 문서화 설정하기

Authors
  • avatar
    Name
    황도연
    Twitter

Description

이 포스팅에서는 NestJS 애플리케이션에서 Swagger를 사용하여 API를 문서화하는 방법을 다룹니다. Swagger는 API의 설계, 빌드, 문서화 및 사용을 위한 오픈소스 도구로, API 개발 과정을 효율적으로 만들어줍니다.

Swagger 모듈 설치

먼저, NestJS 프로젝트에 Swagger 관련 패키지를 설치합니다:

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

Swagger 설정하기

1단계: Swagger 모듈 설정

애플리케이션의 메인 모듈 파일 (예: main.ts)에서 Swagger 모듈을 설정합니다. 다음은 Swagger 문서를 설정하는 기본적인 방법입니다:

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)

  const config = new DocumentBuilder()
    .setTitle('Example API')
    .setDescription('The example API description')
    .setVersion('1.0')
    .addTag('example')
    .build()
  const document = SwaggerModule.createDocument(app, config)
  SwaggerModule.setup('api', app, document)

  await app.listen(3000)
}
bootstrap()

이 설정을 통해 http://localhost:3000/api 주소에서 Swagger UI를 볼 수 있습니다.

2단계: 엔드포인트에 Swagger 데코레이터 추가

NestJS에서 제공하는 Swagger 데코레이터를 사용하여 API 엔드포인트의 설명, 응답 타입 등을 명시할 수 있습니다. 예를 들어, cats.controller.ts 파일에서 다음과 같이 설정할 수 있습니다:

import { Controller, Get } from '@nestjs/common'
import { ApiResponse, ApiTags } from '@nestjs/swagger'

@ApiTags('cats')
@Controller('cats')
export class CatsController {
  @Get()
  @ApiResponse({ status: 200, description: 'Return all cats.' })
  findAll(): string {
    return 'This action returns all cats'
  }
}