본문 바로가기
NestJs

[NestJs] Swagger로 API 문서 작성하기

by teamnova 2024. 4. 23.

안녕하세요. 오늘은 백엔드 개발자라면 작성해야할 API 문서를 Swagger를 통해 손쉽게 작성해 볼게요.

오늘도 가장 먼저 라이브러리를 설치해 보겠습니다.

npm install @nestjs/swagger

먼저 swagger.util.ts 파일을 생성해주세요

 

import { INestApplication } from "@nestjs/common";
import { SwaggerModule, DocumentBuilder, SwaggerCustomOptions } from '@nestjs/swagger';

const swaggerCustomOption: SwaggerCustomOptions = {
    swaggerOptions: {
      persistAuthorization: true,
    },
  };
export function setupSwagger(app: INestApplication): void {
    const options = new DocumentBuilder()
    .setTitle('Stickcode API Docs')
    .setDescription('Stickcode API Docs')
    .setVersion('1.0.0')
    .addBearerAuth(
        {
            type: 'http',
            scheme: 'bearer',
            name: 'JWT',
            in: 'heaer'
        },
        'access-token'
    )
    .build();

    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup('api-docs', app, document, swaggerCustomOption);
}

추후에 JWT토큰도 사용할거라 미리 세팅해놓을게요.

그리고 main.ts입니다.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as dotenv from 'dotenv';
import { setupSwagger } from 'utils/swagger.util';

async function bootstrap() {
  dotenv.config();
  
  const app = await NestFactory.create(AppModule);
  setupSwagger(app);
  await app.listen(3000);
}
bootstrap();

이제 서버를 시작하고 http://localhost:3000/api-docs#/ 여기로 접속해보세요.

아래와 같이 API 문서가 작성될겁니다. 하지만 이렇게만 사용하면 아무 의미가 없고 더 자세히 세팅하는 법은 다음시간에 하겠습니다.