[TIL] 스웨거(Swagger)

김민재·2024년 4월 22일
0

TIL

목록 보기
159/172

Swagger란?

  • API 설계, 구축, 문서화, 테스트 하는 과정을 돕는 프레임워크
  • 주로 API를 직관적인 문서화 할 수 있도록 하는데 활용한다.

express.js에서 swagger 사용하기

nest.js에서 swagger 사용하기

  1. yarn add @nestjs/swagger 패키지 다운로드

  2. main.ts에서 스웨거 설정을 해준다.

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  const config = new DocumentBuilder()
    .setTitle('게시판') // 스웨거 제목
    .setDescription('게시판 API') // 스웨거 설명
    .setVersion('1.0')
    .addTag('board') // CONTROLLER와 매핑된다
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document); // 경로 = localhost:3000/api

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

  1. controller에서 스웨거 API에 맞는 제목을 작성한다. 외 다른 옵션들도 있다.
// dto.ts
export class CreateBoardDto {
    
    @ApiProperty({
        description: '제목',
        required: true,
        example: '제목을 입력해주세요.'
    })
    @IsNotEmpty()
    @MinLength(2)
    @MaxLength(20)
    title: string;

    @ApiProperty({
        description: '내용',
        required: true,
        example: '내용을 입력해주세요.'
    })
    @IsNotEmpty()
    content: string;
}

// controller.ts
@Controller('board')
@ApiTags('board')
export class BoardController {}
profile
개발 경험치 쌓는 곳

0개의 댓글

관련 채용 정보