Swagger란?

API 문서 자동화 도구이다.

왜 필요한가?

보통 API 명세서를 만들고 이 문서를 코드가 수정될때마다 따로 수정을 해주어야한다.

하지만 Swagger를 사용하면 코드를 수정하면 그 결과가 자동으로 api문서에 수정되서 저장이된다.

또한 Api를 테스트 할 수 있는 화면도 제공을 한다. PostMan같은 api테스트 도구를 사용하지 않고 api를 테스트할 수 있다.

정리하자면 API 테스트 & 문서 자동화 도구이다.

사용법

먼저 nestjs에 swagger을 설치해주면 된다.

pnpm install --save @nestjs/swagger

main.ts 에서 SwaggerModule을 이용해서 초기화 해주어야한다.

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({ origin: ['<http://localhost:5173>'] });

  const config = new DocumentBuilder()
    .setTitle('Mini_Post_Project')
    .setDescription('The PostsProject API description')
    .setVersion('1.0')
    .addTag('posts')
    .build();
  const documentFactory = () => SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, documentFactory);
  await app.listen(3000);
}
bootstrap();

위 코드처럼 app.listen() 코드 위에 작성하면 된다.

image.png

그러면 위와같은 화면으로 들어갈 수있다.

이 화면과 코드를 비교해보면 좀더 이해가 쉬울것이다.