42-Swagger
1. Swagger란?
- API Documentation을 제작 할 수 있는 오픈소스 프레임워크다
- 사용자가 직접 API 테스트를 해볼 수 있는 UI 인터페이스를 제공해준다
- RESTful API를 묘사하는 표준적인 방법인 Open API Specification을 따른다
- 현대에 가장 많이 사용하는 API Documenation 프레임워크중 하나다
- NestJS, Spring등 인기있는 대형 프레임워크들이 기본으로 지원하고 있다
2. DocumentBuilder
Swagger Documentation을 초기화하고 생성하는데 사용된다
typescript
1import { NestFactory } from '@nestjs/core'2import { AppModule } from './app.module'3import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'45async function bootstrap() {6const app = await NestFactory.create(AppModule)7const config = new DocumentBuilder()8.setTitle('SNS API')9.setDescription('API documentation for SNS project')10.setVersion('1.0')11.addTag('posts')12.build()13const document = SwaggerModule.createDocument(app, config)14SwaggerModule.setup('api', app, document)15await app.listen(3000)16}17bootstrap()
3. @ApiTags
여러 API를 그룹화하는데 사용된다. 일반적으로 Controller에 직접 적용해서 관련 엔드포인트들을 하나로 묶는다.
typescript
1import { Controller, Get } from '@nestjs/common'2import { ApiTags } from '@nestjs/swagger'34@ApiTags('posts')5@Controller('posts')6export class PostsController {7@Get()8findAll(): string {9return 'This action returns all posts'10}11}
4. @ApiOperation
엔드포인트가 어떤 역할을 하는지 정의 할 수 있다. 짧은 요약을 작성하는데 종종 사용된다.
typescript
1import { Get, Controller } from '@nestjs/common'2import { ApiOperation } from '@nestjs/swagger'34@Controller('posts')5export class PostsController {6@Get()7@ApiOperation({ summary: 'Retrieve all posts' })8findAll(): string {9return 'This action returns all posts'10}11}
5. @ApiResponse
엔드포인트의 응답에 대한 정의를 할 수 있다. 경우의수에 따라 하나 이상 정의 가능하다
typescript
1import { Get, Controller } from '@nestjs/common'2import { ApiResponse } from '@nestjs/swagger'34@Controller('posts')5export class PostsController {6@Get()7@ApiResponse({ status: 200, description: 'Successfully retrieved posts.' })8@ApiResponse({ status: 404, description: 'Posts not found.' })9findAll(): string {10return 'This action returns all posts'11}12}
6. @ApiQuery
API의 쿼리 파라미터에 대한 정의를 할 수 있다.
typescript
1import { Controller, Get, Query } from '@nestjs/common'2import { ApiQuery } from '@nestjs/swagger'34@Controller('posts')5export class PostsController {6@Get()7@ApiQuery({ name: 'author', required: false, type: String })8findAll(@Query('author') author: string): string {9return `This action returns all posts by ${author}`10}11}
7. @ApiParam
API의 Path Parameter에 대한 정의를 할 수 있다
typescript
1import { Controller, Get, Param } from '@nestjs/common'2import { ApiParam } from '@nestjs/swagger'34@Controller('posts')5export class PostsController {6@Get(':id')7@ApiParam({ name: 'id', required: true, type: String })8findOne(@Param('id') id: string): string {9return `This action returns a post with ID ${id}`10}11}
8. @ApiBody
API의 Body에 대한 정의를 할 수 있다
typescript
1import { Controller, Post, Body } from '@nestjs/common'2import { ApiBody } from '@nestjs/swagger'34class CreatePostDto {5title: string6content: string7author: string8}910@Controller('posts')11export class PostsController {12@Post()13@ApiBody({ type: CreatePostDto })14create(@Body() createPostDto: CreatePostDto): string {15return `This action adds a new post : ${createPostDto.title}`16}17}
9. @ApiProperty
Model 또는 DTO의 프로퍼티를 태깅 할 수 있다
typescript
1import { ApiProperty } from '@nestjs/swagger'23export class CreatePostDto {4@ApiProperty({ example: 'My First Post' })5title: string67@ApiProperty({ example: 'This is the content of the post.' })8content: string910@ApiProperty({ example: 'John Doe' })11author: string12}
10. @ApiBearerAuth
Bearer 토큰이 필요한 경우 사용 가능하다.
typescript
1import { Controller, Get } from '@nestjs/common'2import { ApiBearerAuth } from '@nestjs/swagger'34@Controller('posts')5export class PostsController {6@Get()7@ApiBearerAuth()8findAll(): string {9return 'This action returns all posts'10}11}
11. @ApiOAuth2
OAuth가 필요한 경우 사용 할 수 있다
typescript
1import { Controller, Get } from '@nestjs/common'2import { ApiOAuth2 } from '@nestjs/swagger'34@Controller('posts')5export class PostsController {6@Get()7@ApiOAuth2(['read', 'write'])8findAll(): string {9return 'This action returns all posts'10}11}
12. 적용 예제
필요한 기능들을 Annotate 하다보면 코드가 매우 복잡해진다. 특히나 기능과 관련 없는 Annotation이다보니 관리가 부담된다
typescript
1class CreatePostDto {2@ApiProperty({ example: 'My First Post' })3title: string45@ApiProperty({ example: 'This is the content of the post.' })6content: string78@ApiProperty({ example: 'John Doe' })9author: string10}1112@ApiTags('posts')13@Controller('posts')14export class PostsController {15@Get()16@ApiOperation({ summary: 'Retrieve all posts' })17@ApiQuery({ name: 'author', required: false, type: String })18@ApiResponse({ status: 200, description: 'Successfully retrieved posts.' })19findAll(@Query('author') author: string): string {20return `This action returns all posts by ${author}`21}2223@Get(':id')24@ApiOperation({ summary: 'Retrieve a specific post by ID' })25@ApiParam({ name: 'id', required: true, type: String })26@ApiResponse({ status: 200, description: 'Successfully retrieved the post.' })27@ApiResponse({ status: 404, description: 'Post not found.' })28findOne(@Param('id') id: string): string {29return `This action returns a post with ID ${id}`30}3132@Post()33@ApiOperation({ summary: 'Create a new post' })34@ApiBody({ type: CreatePostDto })35@ApiResponse({ status: 201, description: 'The post has been successfully created.' })36create(@Body() createPostDto: CreatePostDto): string {37return `This action adds a new post : ${createPostDto.title}`38}39}
13. Open API CLI Plugin
Typescript의 Reflection 기능을 사용하면 유추 할 수 있는 값들이 많기 때문에, Open API CLI Plugin을 이용하면 많은 기능들을 자동 유추 할 수 있다
json
1{2"collection": "@nestjs/schematics",3"sourceRoot": "src",4"compilerOptions": {5"plugins": ["@nestjs/swagger"]6}7}