solve-my-curiosity

Swagger에 대해 알아보자 본문

Back-End

Swagger에 대해 알아보자

curiosity314 2024. 1. 23. 14:20

Swagger는 API 문서를 자동으로 생성해주는 도구 중 하나이다. Swagger를 사용하여 API 문서를 쉽게 작성하고 관리할 수 있고, 내가 지금하고 있는 프로젝트 백엔드 웹 프레임워크인 nest에서도 swagger를 통합하여 사용할 수 있다.

 

1. 먼저 @nestjs/swagger 패키지를 설치해야 한다.

npm install @nestjs/swagger

 

2. nest의 main.ts 파일 또는 메인 진입점 파일에 다음과 같이 Swagger를 설정한다.

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

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

  // Swagger 설정 시작
  const config = new DocumentBuilder()
    .setTitle('Cats example')
    .setDescription('The cats API description')
    .setVersion('1.0')
    .addTag('cats')
    .addTag('dogs')
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);
  // Swagger 설정 끝

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

DocumentBuilder는 OpenAPI 사양을 준수하는 기본문서를 구성하는데 도움이 된다. 제목, 설명, 버전 등과 같은 속성을 설정할 수 있는 여러 메서드를 제공한다.(코드에서 setTitle, setDescription, setVersion, addTag-> 마지막으로 build())

 

전체 문서를 만들기 위해 createDocument를 사용한다. 이 메소드의 인자에는 애플리케이션 인스턴스와 Swagger 옵션 객체를 사용한다. 그래서 맨 위에서 만든 app과 config를 넣어주면 document가 만들어지고, 이걸 SwaggerModule.setup에 넣어준다.

첫번째 인자는 Swagger UI로 가는 경로 두번째 인자는 애플리케이션 인스턴스 (app) 세번째 인자는 createDocument로 만든 document 문서객체를 넣어준다.

 

2. 이제 Swagger가 사용 가능한 상태이다. 네스트 어플리케이션을 실행하고 브라우저에서 이 주소로 이동하면 Swagger UI가 나타난다.

http://localhost:3000/api
 
대표사진 삭제

사진 설명을 입력하세요.

3. Swagger에서 API 문서를 생성하려면 컨트롤러 클래스에 추가해야 한다. 다음과 같다.

import { Controller, Get } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';

@ApiTags('cats') // 'cats' 태그에 속하는 API들
@Controller('cats')
export class CatsController {
  @Get()
  findAll(): string {
    return 'This action returns all cats';
  }
}

@ApiTags('dogs') // 'dogs' 태그에 속하는 API들
@Controller('dogs')
export class DogsController {
  @Get()
  findAll(): string {
    return 'This action returns all dogs';
  }
}
 

4. 실행중인 애플리케이션에서 /api 라우트로 Swagger UI에 접속하면 컨트롤러 및 메소드의 API 문서가 표시된다.

 

**Tag란 무엇일까??**

태그는 Swagger를 사용하여 API 문서를 작성할 때, API를 그룹화하고 정리하는데 사용되는 metadata 이다. API문서에서 API를 쉽게 찾고 구분할 수 있도록 도와주는 역할이다.

Swagger에서 태그를 사용하려면 @nestjs/swagger 패키지에서 제공하는 @ApiTags() 데코레이터를 사용하면 된다. 이 데코레이터는 컨트롤러 클래스에 사용하여 해당 컨트롤러와 관련된 API들을 그룹화하는데 사용한다.

 

**서비스나 메소드에 대해서는??**

서비스나 메소드에 대해서는 다른 데코레이터들을 사용하여 Swagger 문서를 추가로 정의할 수 있다.

예를 들어, API 응답과 용청 모델을 설명하기 위해 @ApiResponse(), @ApiOperation(), @ApiBody()등의 데코레이터를 사용할 수 있다.

컨트롤러-@ApiTags()

메소드-@ApiOperation()-메소드의 기능 및 설명 추가

메소드-@ApiResponse()-API 응답을 정의

메소드-@ApiBody()-API 요청 바디를 정의

예시 코드

import { Controller, Get, Post, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';
import { CreateCatDto } from './dto/create-cat.dto';
import { Cat } from './interfaces/cat.interface';
import { CatsService } from './cats.service';

@ApiTags('cats') // 컨트롤러에 대한 태그를 설정합니다.
@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  @ApiOperation({ summary: 'Get all cats', description: 'Retrieve all cats from the database.' })
  @ApiResponse({ status: 200, description: 'Success', type: Cat, isArray: true })
  findAll(): Cat[] {
    return this.catsService.findAll();
  }

  @Post()
  @ApiOperation({ summary: 'Create a new cat', description: 'Create a new cat and add it to the database.' })
  @ApiResponse({ status: 201, description: 'The cat has been successfully created.', type: Cat })
  @ApiResponse({ status: 400, description: 'Bad Request' })
  create(@Body() createCatDto: CreateCatDto): Cat {
    return this.catsService.create(createCatDto);
  }
}
 

 

 

 

 

출처 : nestjs 공식문서

https://docs.nestjs.com/openapi/introduction