728x90
안녕하세요. 오늘은 백엔드 개발자라면 작성해야할 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 문서가 작성될겁니다. 하지만 이렇게만 사용하면 아무 의미가 없고 더 자세히 세팅하는 법은 다음시간에 하겠습니다.
'NestJs' 카테고리의 다른 글
[NestJs] 게시물에 시간 추가하기 (0) | 2024.04.14 |
---|---|
[NestJs] TypeORM을 사용해서 게시물 CRUD 만들기 (0) | 2024.04.05 |
[NestJs] TypeORM 설치 및 설정하기 (0) | 2024.03.27 |
[NestJs] 게시물 수정 및 삭제하기 (0) | 2024.03.18 |
[NestJs] ValidationPipe로 유효성 검사하기 (0) | 2024.03.09 |