NestJS에 Swagger(스웨거) Document(문서)를 적용

 이제 본격적으로 Swagger를 이용하여 자동 API Document를 작성하도록 하겠습니다. 기본적으로 nestjs가 설치됬다는 가정하에 진행을 하도록 하겠습니다. 만약 설치방법이 궁금하시면 아래 링크를 참고해 주시기 바랍니다.


링크 : NestJS 설치법


먼저 npm모듈을 설치합니다.


npm i @nestjs/swagger swagger-ui-express


위 두개의 모듈은 각각 nestjs 지원 및 프런트 화면구성을 위한 swagger모듈 입니다.


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

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

// Swagger Document를 설정
const options = new DocumentBuilder()
.setTitle('nest API')
.setVersion('1.0')
.build();

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


위의 코드와 같이 main.ts파일을 수정합니다. 위 코드에서 추가된 것은 DocumentBuilder class이며 이는 API문서를 만들기 위한 준비사항 입니다. 해당 문서의 제목(setTitle), 버전(setVersion) 그리고 빌드(build)를 합니다.


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

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

// Swagger Document를 설정
const options = new DocumentBuilder()
.setTitle('nest API')
.setVersion('1.0')
.build();

// Swagger Document의 문서를 api(/api-docs)로 설정할수 있게 셋팅
const document = SwaggerModule.createDocument(app, options);
SwaggerModule.setup('api-docs', app, document);

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


이제 위 코드에서 document변수를 이용하여 문서를 생성합니다. 'SwaggerModule.createDocument'의 첫번째 인자는 해당 서버 앱, 두번째는 셋팅한 Swagger option 변수 입니다. 그리고 마지막으로 SwaggerModule.setup을 하면 서버 실행과 동시에 web Document가 생성이 됩니다. 이때에서 첫번째 인자는 root url다음에 올 카워드로 이는 서버에서 API문서를 제공하기 위한 Swagger API입니다. 위 코드에서는 'api-docs'이기 때문에 실제 경로는 'root url/api-docs' 입니다.



이제 해당 url(위 예시에서는 'localhost:3000/api-docs')에 접속하면 default API문서가 생성됩니다. 다음에는 실제 API를 만들면서 Swagger를 적용하여 자동 Document를 작성하도록 하겠습니다.


(이전글)

(다음글)

댓글

이 블로그의 인기 게시물

DAQ로 전압 측정하기-2

Nest JS URL에 있는 쿼리(Query) 읽기

appendChild를 이용하여
  • 늘리기_JavaScript_2번