끄적이는 개발노트

NestJS - Swagger 본문

JavaScript/NestJS

NestJS - Swagger

크런키스틱 2025. 5. 23. 19:17
728x90

백엔드 API 개발 시에 개발한 API 정보를 시각적으로 표현하고 공유하기 위해 API 문서를 만든다. 그 중 Swagger라는 툴을 통해 만들 수 있는데 NestJS에도 적용이 가능하다. 이를 통해 특정 페이지를 통해서 API의 엔드포인트, 스키마, DTO 등에 대한 정보를 시각적으로 편리하게 알아볼 수 있다.

 

업무 시에도 백엔드 담당 개발자 분이 Swagger를 사용해 API를 공유해서 편리하게 API를 연동한 경험이 있고, 본인 역시 업무에서 서브로 백엔드를 담당해 일부 개발할 때 문서에 맞게 Swagger를 작성한 경험이 있다. 그렇기 때문에 개인 프로젝트를 진행할 때도 Swagger를 적용하고 있다.

 

https://swagger.io/

 

API Documentation & Design Tools for Teams | Swagger

Swagger and OpenAPI go hand‑in‑hand. Swagger offers powerful and easy to use tools to take full advantage of the OpenAPI Specification. See how we do it

swagger.io

https://docs.nestjs.com/openapi/introduction

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

 

1. 설치

npm i @nestjs/swagger
#or
yarn add @nestjs/swagger

 

 

2. 적용

main.ts

// main.ts

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

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

  // Swagger Setting
  const config = new DocumentBuilder()
    .setTitle("API Docs") // Swagger 제목
    .setDescription('API 문서입니다.') // Swagger 설명
    .setVersion('1.0.0') // API Version
    .build();
  const documentFactory = () => SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, documentFactory); // swagger 표시할 path 설정(ex. http://localhost:3001/api)

  ...
}
bootstrap();

 

위 코드와 같이 title, description 등 원하는 세팅을 메소드를 사용해서 설정해주면 된다.

중요한 것은 SwaggerModule.setup()이다.

첫번째 인자로 swagger가 표시될 path를 지정해준다.

두번째 인자로 생성한 NestJS App을 넣어준다.

세번째 인자로는 생성한 SwaggerApi 객체를 넣어주면 된다.

 

 

create-schedule.dto.ts

// create-schedule.dto.ts

import { ApiProperty } from '@nestjs/swagger';
import {
  IsDateString,
  IsNotEmpty,
  IsOptional,
  IsString,
} from 'class-validator';

export class CreateScheduleDto {
  @ApiProperty({ description: '제목' })
  @IsNotEmpty()
  @IsString()
  readonly title: string;

  @ApiProperty({ description: '시작 일시' })
  @IsNotEmpty()
  @IsDateString()
  readonly startAt: Date;

  @ApiProperty({ description: '내용', required: false })
  @IsOptional()
  @IsString()
  readonly contents: string;
}

 

DTO를 본인이 생각한 타입이나 속성에 맞게끔 데코레이터를 사용하면 된다.

  • @ApiProperty : 필드에 대한 설명
  • @IsString : 필드 타입이 string
  • @IsNotEmpty : 필드값 필수
  • @IsOptional : 필드값 필수 x

정말 간단한 예시로 사용한 데코레이터가 적지만, 이 외에도 정말 많은 데코레이터들이 있으니 필요에 따라 찾아 사용하면 된다.

(IsNumber, IsArray 등등 타입부터 옵션에 대한 데코레이터가 정말 많다.)

 

 

schedule.controller.ts

// schedule.controller.ts

import { Body, Controller, Get, Post } from '@nestjs/common';
import { ScheduleService } from './schedule.service';
import { CreateScheduleDto } from './dto/create-schedule.dto';
import { Schedule } from 'src/schemas/schedule.schema';
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';

@ApiTags('Schedule')
@Controller(ApiPath.SCHEDULE)
export class ScheduleController {
  constructor(private readonly scheduleService: ScheduleService) {}

  @ApiOperation({ summary: '스케줄 추가 API' })
  @ApiBody({ description: '스케줄 데이터', type: CreateScheduleDto })
  @Post()
  async create(@Body() scheduleData: CreateScheduleDto): Promise<Schedule> {
    return await this.scheduleService.create(scheduleData);
  }

  @ApiOperation({ summary: '스케줄 전체 리스트 반환 API' })
  @Get()
  async getScheduleList(): Promise<Schedule[]> {
    return await this.scheduleService.getScheduleList();
  }
}

 

이제 controller에 필요한 데코레이터를 사용하면 된다. 주로 사용되는 것을 살펴보면 다음과 같다. 이외에도 다양한 데코레이터가 있는데 이는 공식문서를 참고하면서 필요한 것을 사용하면 된다.

  • @ApiTags : tag 생성, controller에 위치하면 속한 api들이 해당 태그 아래에 나타난다.
  • @ApiOperation : API 설명
  • @ApiResponse : API의 Response 값에 대한 설명
  • @ApiQuery : API의 Query로 받을 값에 대한 설명
  • @ApiParam : API의 Param으로 받을 값에 대한 설명
  • @ApiBody : API의 Body로 받을 값에 대한 설명

 

3. 실행

아래와 같이 API 문서가 보기 좋게 생성된 것을 확인할 수 있다.

 

728x90

'JavaScript > NestJS' 카테고리의 다른 글

NestJS - bcrypt  (0) 2023.06.23
NestJS - 알림톡 전송 (SOLAPI)  (0) 2023.06.22
NestJS - JWT 토큰 기반 인증 구현 (2)  (0) 2023.06.19
NestJS - JWT 토큰 기반 인증 구현 (1)  (0) 2023.06.19
NestJS - Middleware  (0) 2021.11.03