Skip to Content
BackendNestJs42-Swagger

1. Swagger란?

  • API Documentation을 제작 할 수 있는 오픈소스 프레임워크다
  • 사용자가 직접 API 테스트를 해볼 수 있는 UI 인터페이스를 제공해준다
  • RESTful API를 묘사하는 표준적인 방법인 Open API Specification을 따른다
  • 현대에 가장 많이 사용하는 API Documenation 프레임워크중 하나다
  • NestJS, Spring등 인기있는 대형 프레임워크들이 기본으로 지원하고 있다

2. DocumentBuilder

Swagger Documentation을 초기화하고 생성하는데 사용된다

typescript
1
import { NestFactory } from '@nestjs/core'
2
import { AppModule } from './app.module'
3
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'
4
5
async function bootstrap() {
6
const app = await NestFactory.create(AppModule)
7
const config = new DocumentBuilder()
8
.setTitle('SNS API')
9
.setDescription('API documentation for SNS project')
10
.setVersion('1.0')
11
.addTag('posts')
12
.build()
13
const document = SwaggerModule.createDocument(app, config)
14
SwaggerModule.setup('api', app, document)
15
await app.listen(3000)
16
}
17
bootstrap()

3. @ApiTags

여러 API를 그룹화하는데 사용된다. 일반적으로 Controller에 직접 적용해서 관련 엔드포인트들을 하나로 묶는다.

typescript
1
import { Controller, Get } from '@nestjs/common'
2
import { ApiTags } from '@nestjs/swagger'
3
4
@ApiTags('posts')
5
@Controller('posts')
6
export class PostsController {
7
@Get()
8
findAll(): string {
9
return 'This action returns all posts'
10
}
11
}

4. @ApiOperation

엔드포인트가 어떤 역할을 하는지 정의 할 수 있다. 짧은 요약을 작성하는데 종종 사용된다.

typescript
1
import { Get, Controller } from '@nestjs/common'
2
import { ApiOperation } from '@nestjs/swagger'
3
4
@Controller('posts')
5
export class PostsController {
6
@Get()
7
@ApiOperation({ summary: 'Retrieve all posts' })
8
findAll(): string {
9
return 'This action returns all posts'
10
}
11
}

5. @ApiResponse

엔드포인트의 응답에 대한 정의를 할 수 있다. 경우의수에 따라 하나 이상 정의 가능하다

typescript
1
import { Get, Controller } from '@nestjs/common'
2
import { ApiResponse } from '@nestjs/swagger'
3
4
@Controller('posts')
5
export class PostsController {
6
@Get()
7
@ApiResponse({ status: 200, description: 'Successfully retrieved posts.' })
8
@ApiResponse({ status: 404, description: 'Posts not found.' })
9
findAll(): string {
10
return 'This action returns all posts'
11
}
12
}

6. @ApiQuery

API의 쿼리 파라미터에 대한 정의를 할 수 있다.

typescript
1
import { Controller, Get, Query } from '@nestjs/common'
2
import { ApiQuery } from '@nestjs/swagger'
3
4
@Controller('posts')
5
export class PostsController {
6
@Get()
7
@ApiQuery({ name: 'author', required: false, type: String })
8
findAll(@Query('author') author: string): string {
9
return `This action returns all posts by ${author}`
10
}
11
}

7. @ApiParam

API의 Path Parameter에 대한 정의를 할 수 있다

typescript
1
import { Controller, Get, Param } from '@nestjs/common'
2
import { ApiParam } from '@nestjs/swagger'
3
4
@Controller('posts')
5
export class PostsController {
6
@Get(':id')
7
@ApiParam({ name: 'id', required: true, type: String })
8
findOne(@Param('id') id: string): string {
9
return `This action returns a post with ID ${id}`
10
}
11
}

8. @ApiBody

API의 Body에 대한 정의를 할 수 있다

typescript
1
import { Controller, Post, Body } from '@nestjs/common'
2
import { ApiBody } from '@nestjs/swagger'
3
4
class CreatePostDto {
5
title: string
6
content: string
7
author: string
8
}
9
10
@Controller('posts')
11
export class PostsController {
12
@Post()
13
@ApiBody({ type: CreatePostDto })
14
create(@Body() createPostDto: CreatePostDto): string {
15
return `This action adds a new post : ${createPostDto.title}`
16
}
17
}

9. @ApiProperty

Model 또는 DTO의 프로퍼티를 태깅 할 수 있다

typescript
1
import { ApiProperty } from '@nestjs/swagger'
2
3
export class CreatePostDto {
4
@ApiProperty({ example: 'My First Post' })
5
title: string
6
7
@ApiProperty({ example: 'This is the content of the post.' })
8
content: string
9
10
@ApiProperty({ example: 'John Doe' })
11
author: string
12
}

10. @ApiBearerAuth

Bearer 토큰이 필요한 경우 사용 가능하다.

typescript
1
import { Controller, Get } from '@nestjs/common'
2
import { ApiBearerAuth } from '@nestjs/swagger'
3
4
@Controller('posts')
5
export class PostsController {
6
@Get()
7
@ApiBearerAuth()
8
findAll(): string {
9
return 'This action returns all posts'
10
}
11
}

11. @ApiOAuth2

OAuth가 필요한 경우 사용 할 수 있다

typescript
1
import { Controller, Get } from '@nestjs/common'
2
import { ApiOAuth2 } from '@nestjs/swagger'
3
4
@Controller('posts')
5
export class PostsController {
6
@Get()
7
@ApiOAuth2(['read', 'write'])
8
findAll(): string {
9
return 'This action returns all posts'
10
}
11
}

12. 적용 예제

필요한 기능들을 Annotate 하다보면 코드가 매우 복잡해진다. 특히나 기능과 관련 없는 Annotation이다보니 관리가 부담된다

typescript
1
class CreatePostDto {
2
@ApiProperty({ example: 'My First Post' })
3
title: string
4
5
@ApiProperty({ example: 'This is the content of the post.' })
6
content: string
7
8
@ApiProperty({ example: 'John Doe' })
9
author: string
10
}
11
12
@ApiTags('posts')
13
@Controller('posts')
14
export 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.' })
19
findAll(@Query('author') author: string): string {
20
return `This action returns all posts by ${author}`
21
}
22
23
@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.' })
28
findOne(@Param('id') id: string): string {
29
return `This action returns a post with ID ${id}`
30
}
31
32
@Post()
33
@ApiOperation({ summary: 'Create a new post' })
34
@ApiBody({ type: CreatePostDto })
35
@ApiResponse({ status: 201, description: 'The post has been successfully created.' })
36
create(@Body() createPostDto: CreatePostDto): string {
37
return `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
}