본문 바로가기

Swagger를 이용한 API 문서화

사용자 API의 컨트롤러와 DTO에서 OpenAPI 문서를 만들어 Swagger UI로 확인하고, 문서와 실제 동작이 어긋나는 지점을 찾아 맞춥니다.

API를 만들고 나면 그것을 쓸 사람이 묻습니다. 목록은 어느 주소로 요청하는지, 생성할 때 어떤 필드를 보내야 하는지, 실패하면 무엇이 돌아오는지입니다. 답을 위키에 손으로 적어 두면 코드가 바뀔 때마다 문서도 따라 고쳐야 하고, 한 번만 잊어도 문서와 서버가 서로 다른 말을 합니다. 이 글에서는 앞 글까지 만든 컨트롤러와 DTO에서 문서를 뽑아내는 방법을 다룹니다.

이 글을 읽고 나면 다음을 할 수 있습니다.

  • @nestjs/swagger로 Swagger UI와 OpenAPI 명세를 서버에 띄웁니다.
  • DTO와 컨트롤러에 데코레이터를 달아 요청·응답의 모양과 상태 코드를 문서에 드러냅니다.
  • 문서 데코레이터가 바꾸는 것과 바꾸지 못하는 것을 구별하고, 어긋난 문서를 고칩니다.

앞 글의 users-api 프로젝트를 이어서 씁니다. 전역 접두사는 없고 경로는 /v1/users이며, 전역 ValidationPipe가 켜져 있습니다. npm run start:dev로 서버를 켜 두고 브라우저를 함께 씁니다.


코드에서 문서를 뽑아내기

OpenAPI는 HTTP API의 경로, 입력, 응답을 JSON이나 YAML로 적는 표준 형식입니다. 프로그래밍 언어와 상관없이 도구가 읽을 수 있어서, 이 명세 하나로 문서 화면을 그리거나 클라이언트 코드를 생성할 수 있습니다. Swagger는 이 형식을 다루는 도구 모음이고, 그 가운데 Swagger UI가 명세를 사람이 읽는 화면으로 보여 줍니다. NestJS의 @nestjs/swagger 패키지는 컨트롤러와 DTO에 이미 있는 정보를 읽어 OpenAPI 문서를 만듭니다. NestJS 12에 맞는 현재 버전은 12.1입니다.

npm install @nestjs/swagger

main.ts에 문서 설정을 더합니다. @nestjs/swagger의 import와, listen() 바로 앞의 config부터 SwaggerModule.setup()까지가 새로 들어간 부분입니다.

src/main.ts
import { ValidationPipe, VersioningType } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { AppModule } from './app.module';

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

  app.enableVersioning({ type: VersioningType.URI });

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
    }),
  );

  const config = new DocumentBuilder()
    .setTitle('Users API')
    .setDescription('5장에서 만드는 사용자 API')
    .setVersion('1.0')
    .build();
  const documentFactory = () => SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, documentFactory);

  await app.listen(process.env.PORT ?? 3000);
}

void bootstrap();

DocumentBuilder는 제목과 설명처럼 문서 전체에 해당하는 정보를 만듭니다. SwaggerModule.createDocument(app, config)는 애플리케이션에 등록된 컨트롤러와 DTO를 훑어 문서 객체를 만들고, SwaggerModule.setup('api', app, documentFactory)는 그 문서를 /api에 Swagger UI로 띄웁니다. createDocument()를 함수로 감싸 넘기면 문서는 누군가 처음 요청할 때 만들어집니다.

이제 주소가 세 개 생겼습니다. http://localhost:3000/api는 사람이 보는 화면이고, /api-json과 /api-yaml은 도구가 읽는 명세입니다. 실제 API는 여전히 /v1/users에 있습니다. setVersion('1.0')은 문서에 적히는 버전 표기일 뿐 URI의 v1과는 관계가 없습니다.

브라우저에서 http://localhost:3000/api를 열면 앞 글까지 만든 사용자 API의 엔드포인트가 모두 보입니다. 데코레이터를 하나도 달지 않았는데도 경로와 메서드가 나오는 것은 @Controller()와 @Get() 같은 기존 정보를 읽었기 때문입니다. 그런데 POST /v1/users를 펼쳐 요청 본문의 스키마를 보면 CreateUserDto가 속성이 하나도 없는 빈 객체로 나옵니다. 응답 쪽도 상태 코드만 있고 모양이 없습니다. 이 문서로는 무엇을 보내야 하는지 알 수 없습니다.


DTO의 속성을 문서에 드러내기

TypeScript가 실행 시점에 남기는 정보만으로는 클래스에 어떤 속성이 있는지 알 수 없습니다. 그래서 문서에 내보낼 속성마다 @ApiProperty()를 붙여 알려 줍니다. 앞 글의 검증 데코레이터는 그대로 두고 한 줄씩 더합니다.

src/users/dto/create-user.dto.ts
import { ApiProperty } from '@nestjs/swagger';
import { Transform } from 'class-transformer';
import { IsEmail, IsString, Length, MaxLength } from 'class-validator';

export class CreateUserDto {
  @ApiProperty({ description: '사용자 이름', example: '홍길동', maxLength: 80 })
  @Transform(({ value }) =>
    typeof value === 'string' ? value.trim() : value,
  )
  @IsString()
  @Length(1, 80)
  name!: string;

  @ApiProperty({
    description: '사용자 이메일',
    example: '[email protected]',
    maxLength: 254,
  })
  @Transform(({ value }) =>
    typeof value === 'string' ? value.trim() : value,
  )
  @IsEmail()
  @MaxLength(254)
  email!: string;
}

수정용 DTO는 PartialType을 가져오는 패키지만 바꿉니다. @nestjs/swagger의 PartialType은 검증 규칙과 함께 @ApiProperty() 정보도 이어받으므로, 문서에서도 두 필드가 선택 항목으로 나옵니다. 필드 생략은 허용하고 null은 거부하는 동작은 그대로입니다.

src/users/dto/update-user.dto.ts
import { PartialType } from '@nestjs/swagger';
import { CreateUserDto } from './create-user.dto';

export class UpdateUserDto extends PartialType(CreateUserDto, {
  skipNullProperties: false,
}) {}

응답의 모양도 문서에 그리려면 실행 시점에 남는 클래스가 필요합니다. 지금의 UsersPageResponse는 인터페이스라서 쓸 수 없으므로, 문서에서 참조할 모델 클래스를 새 파일에 둡니다.

src/users/dto/users-response.model.ts
import { ApiProperty } from '@nestjs/swagger';

export class UserResponseModel {
  @ApiProperty({ example: 1 })
  id!: number;

  @ApiProperty({ example: 'Alice' })
  name!: string;

  @ApiProperty({ example: '[email protected]' })
  email!: string;
}

export class UsersPageResponseModel {
  @ApiProperty({ type: [UserResponseModel] })
  items!: UserResponseModel[];

  @ApiProperty({ example: 1, minimum: 1 })
  page!: number;

  @ApiProperty({ example: 20, minimum: 1, maximum: 100 })
  limit!: number;

  @ApiProperty({ example: 2, minimum: 0 })
  total!: number;
}

배열 속성은 type: [UserResponseModel]처럼 항목의 타입을 직접 적어야 합니다. 이 두 클래스는 문서에만 쓰입니다. 실제 응답은 계속 UserResponseDto.from()이 만들고, 서비스의 UserRecord도 그대로입니다.


컨트롤러에 요약과 응답을 적기

컨트롤러에는 엔드포인트가 무엇을 하고 어떤 상태 코드로 답하는지를 적습니다. 먼저 @nestjs/swagger와 모델을 가져오고, 클래스에 @ApiTags()를, 목록과 생성 핸들러에 요약과 응답을 붙입니다. 핸들러의 본문은 건드리지 않습니다.

src/users/users.controller.ts (바뀐 부분)
import {
  ApiOperation,
  ApiQuery,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import {
  UserResponseModel,
  UsersPageResponseModel,
} from './dto/users-response.model';

@ApiTags('users')
@Controller({ path: 'users', version: '1' })
export class UsersController {
  // ...

  @Get()
  @ApiOperation({ summary: '사용자 목록 조회' })
  @ApiQuery({
    name: 'page',
    required: false,
    schema: { type: 'integer', minimum: 1, default: 1 },
  })
  @ApiQuery({
    name: 'limit',
    required: false,
    schema: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
  })
  @ApiResponse({
    status: 200,
    description: '빈 목록도 같은 구조입니다.',
    type: UsersPageResponseModel,
  })
  @ApiResponse({ status: 400, description: 'page 또는 limit 검증 실패' })
  findAll(@Query() query: ListUsersQueryDto): UsersPageResponse {
    // 그대로
  }

  @Post()
  @ApiOperation({ summary: '사용자 생성' })
  @ApiResponse({
    status: 201,
    description: 'Location 헤더에 새 사용자의 주소가 담깁니다.',
    type: UserResponseModel,
  })
  @ApiResponse({ status: 400, description: '본문 검증 실패' })
  @ApiResponse({ status: 409, description: '이미 쓰는 이메일' })
  create(
    @Body() dto: CreateUserDto,
    @Res({ passthrough: true }) response: Response,
  ): UserResponseDto {
    // 그대로
  }
}
  • @ApiTags('users')는 이 컨트롤러의 엔드포인트를 화면에서 users 묶음 아래에 모읍니다.
  • @ApiOperation()은 엔드포인트의 요약과 설명을 붙입니다.
  • @ApiResponse()는 상태 코드별 응답을 적고, type에 클래스를 주면 그 응답의 스키마가 함께 표시됩니다.
  • @ApiQuery()는 쿼리 매개변수의 이름과 범위, 기본값을 적습니다.

요청 본문과 :id는 따로 적지 않았습니다. @Body() dto: CreateUserDto와 @Param('id')를 Swagger가 읽어 문서의 요청 본문과 매개변수를 채우기 때문입니다. 설명이나 예시를 더 붙이고 싶을 때만 @ApiBody()와 @ApiParam()을 씁니다.

저장한 뒤 /api를 새로 고치면 users 묶음이 생기고, 생성 엔드포인트의 요청 본문에 name과 email이 예시와 함께 보입니다. 목록 엔드포인트를 펼쳐 Try it out을 누르고 Execute를 누르면 Swagger UI가 실행 중인 서버에 실제 요청을 보내고 응답을 보여 줍니다. 응답의 items, page, limit, total이 문서의 스키마와 같은지 비교해 보세요.

Nest OpenAPI · 문서 생성

코드 옆 metadata를 문서로 모으고 실제 동작과 대조합니다

createDocument()가 전역 설정·라우트·모델의 runtime metadata를 탐색해 OpenAPI 문서를 만듭니다. 문서의 보안·검증·응답 선언을 실제 Guard·Pipe·직렬화 구현과 별도로 확인합니다.

Nest 메타데이터에서 OpenAPI 문서와 소비자로 이어지는 흐름 DocumentBuilder의 기본 문서 설정, Controller의 경로와 operation 메타데이터, DTO 및 응답 모델의 schema 메타데이터가 createDocument에 모입니다. 만들어진 OpenAPI 문서는 Swagger UI와 JSON·YAML 기반 도구가 함께 사용합니다. OPENAPI DocumentBuilder info · tags · securitySchemes Controller metadata route · operation · response DTO · response model schema · example · required createDocument() 애플리케이션 메타데이터 탐색 SwaggerModule OpenAPI Document serializable JSON · YAML Swagger UI read · authorize · try it out Clients · tools SDK · tests · gateways
문서 메타데이터 세 원천과 두 소비 경로 DocumentBuilder 전역 설정, Controller 라우트/operation/response, DTO와 응답 모델 schema가 createDocument에 따로 모입니다. 생성된 OpenAPI는 사람이 읽는 Swagger UI와 도구 입력인 명세로 갈라집니다. 선은 문서 정보의 흐름이며 실제 Guard/Pipe를 실행하는 제어 흐름이 아닙니다. DocumentBuilder 문서 정보 · 보안 스키마 Controller metadata 경로 · operation · 응답 DTO 모델 metadata schema · 필드 예시 createDocument() 세 원천을 탐색 OpenAPI Document 직렬화 가능 JSON / YAML 사람 Swagger UI 실제 요청 도구 SDK · 테스트 명세 입력
  1. 1 · 메타데이터 원천

    DocumentBuilder는 문서 전역 정보와 보안 스키마를, Controller는 라우트와 operation을, DTO·응답 모델 class는 schema를 제공합니다.

  2. 2 · 문서 생성

    createDocument()가 세 원천을 탐색해 하나의 직렬화 가능한 OpenAPI Document를 만듭니다.

  3. 3 · 사람을 위한 UI

    Swagger UI는 operation과 schema를 읽고, 인증 값을 넣거나 실제 API로 Try it out 요청을 보냅니다.

  4. 4 · 도구를 위한 명세

    JSON·YAML 명세는 SDK 생성, 명세 대조 테스트, API gateway 같은 자동화 도구의 입력이 됩니다.

OpenAPI 메타데이터는 동작을 설명합니다. 입력 검증은 Pipe, 접근 제어는 Guard, 응답 변환은 serializer와 exception layer가 실제 런타임에서 수행하며 문서와 계속 일치시켜야 합니다.

지금까지 손댄 세 곳이 그림 왼쪽의 세 출처입니다. DocumentBuilder는 문서 전체의 정보를, 컨트롤러는 경로와 엔드포인트 정보를, DTO와 응답 모델은 스키마를 내놓고, createDocument()가 이를 하나의 문서로 묶습니다. 완성된 문서는 사람이 보는 Swagger UI와 도구가 읽는 JSON·YAML 명세로 쓰입니다. 그림의 선은 문서 정보가 흐르는 방향이며 요청이 처리되는 순서가 아닙니다.


문서에 적는다고 동작이 바뀌지는 않습니다

삭제는 아무나 하면 안 되는 작업이니 문서에 "토큰이 필요하다"고 적어 보겠습니다. main.ts의 DocumentBuilder에 Bearer 인증 방식을 정의하고, 삭제 핸들러에 @ApiBearerAuth()를 붙입니다. 두 곳의 이름 'access-token'은 글자까지 같아야 합니다.

src/main.ts (바뀐 부분)
  const config = new DocumentBuilder()
    .setTitle('Users API')
    .setDescription('5장에서 만드는 사용자 API')
    .setVersion('1.0')
    .addBearerAuth({ type: 'http', scheme: 'bearer' }, 'access-token')
    .build();
src/users/users.controller.ts (삭제 핸들러)
  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiBearerAuth('access-token')
  @ApiOperation({ summary: '사용자 삭제' })
  @ApiResponse({ status: 204, description: '응답 본문 없음' })
  remove(@Param('id', ParseIntPipe) id: number): void {
    // 그대로
  }

@nestjs/swagger의 import에 ApiBearerAuth를 더합니다. 문서를 새로 고치면 삭제 엔드포인트에 자물쇠가 붙습니다. 이 상태에서 토큰 없이 curl -i -X DELETE http://localhost:3000/v1/users/2를 보내면 어떻게 될까요? 먼저 예상해 보세요.

결과 확인하기

204가 돌아오고 Bob이 지워집니다. @ApiBearerAuth()는 문서에 "이 엔드포인트는 인증이 필요하다"고 적을 뿐, 요청을 막는 코드를 실행하지 않습니다. 요청을 실제로 막는 것은 가드입니다.

문서에 적은 대로 동작하게 하려면 가드를 붙여야 합니다. 4장의 JWT 가드 대신, 여기서는 정해 둔 토큰 하나만 확인하는 학습용 가드를 만듭니다.

src/common/demo-token.guard.ts
import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import type { Request } from 'express';

@Injectable()
export class DemoTokenGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest<Request>();

    if (request.headers.authorization !== 'Bearer demo-token') {
      throw new UnauthorizedException();
    }
    return true;
  }
}

삭제 핸들러의 @ApiBearerAuth('access-token') 위에 @UseGuards(DemoTokenGuard)를 붙이고, UseGuards와 DemoTokenGuard를 가져옵니다. 문서에도 @ApiResponse({ status: 401, description: '토큰이 없거나 틀림' })을 더합니다. 이제 토큰 없는 삭제는 401이고, 헤더를 붙이면 204입니다.

curl -i -X DELETE http://localhost:3000/v1/users/2 -H "Authorization: Bearer demo-token"

이 명령은 PowerShell에서도 curl을 curl.exe로만 바꾸면 됩니다. Swagger UI에서는 화면 위쪽의 Authorize를 눌러 demo-token을 입력합니다. 그 뒤로 자물쇠가 붙은 엔드포인트의 Try it out 요청에 Authorization: Bearer demo-token 헤더가 실립니다.

Nest Swagger · 선언과 런타임 역할

선언 위치, OpenAPI 결과, 실제 실행 역할을 함께 확인합니다

각 선언은 API 명세를 기록합니다. Guard·Pipe·serializer가 실제 동작을 수행하므로 같은 schema와 상태 코드를 만드는지 대조합니다. Try it out은 실제 API 요청을 보냅니다.

문서 전역

선언: DocumentBuilder
OpenAPI에 남는 결과: info, tags, securitySchemes
런타임에서 별도로 확인할 것: 서버 동작이나 인증을 적용하지 않음

DTO · 응답 모델

선언: @ApiProperty() 또는 CLI plugin
OpenAPI에 남는 결과: components.schemas의 property와 제약
런타임에서 별도로 확인할 것:
요청 DTO
class-validator · Pipe
응답 · serializer 대조

Handler 입력

선언: @Body(), @Param(), 필요 시 @ApiBody()·@ApiParam()
OpenAPI에 남는 결과: requestBody와 parameters
런타임에서 별도로 확인할 것: Pipe가 파싱·변환·검증을 수행

Controller · Handler

선언: @ApiTags(), @ApiOperation()
OpenAPI에 남는 결과: tag, summary, description
런타임에서 별도로 확인할 것: 라우트 처리 결과를 바꾸지 않음

응답 명세

선언: @ApiResponse()
OpenAPI에 남는 결과: 상태 코드별 response와 schema
런타임에서 별도로 확인할 것: 실제 예외·직렬화 결과와 대조

보호된 operation

선언:
addBearerAuth()
@ApiBearerAuth(name)

DocumentBuilder와 operation에 같은 scheme 이름을 사용합니다.

OpenAPI에 남는 결과: 보안 스키마와 operation의 security requirement
런타임에서 별도로 확인할 것: Guard가 실제 접근을 허용하거나 차단

검수 순서는 단순합니다. 실제 route와 DTO를 기준으로 OpenAPI 문서를 비교하고, UI의 Try it out 또는 명세 대조 테스트로 요청·응답·인증 조건이 일치하는지 확인합니다.

표는 선언하는 자리마다 문서에 무엇이 남고, 실제 동작은 누가 맡는지를 나란히 적은 것입니다. @ApiProperty()의 maxLength는 문서의 제약이고 실제 검사는 class-validator와 파이프가 합니다. @ApiBearerAuth()는 문서의 보안 요구이고 실제 차단은 가드가 합니다. 그래서 문서를 고친 뒤에는 Try it out이나 curl로 실제 응답과 맞는지 확인해야 합니다.

결과가 다를 때는 다음을 확인합니다.

증상먼저 볼 곳
/api가 404SwaggerModule.setup()이 listen()보다 앞에 있는지, @nestjs/swagger를 설치했는지
스키마가 빈 객체로 나옴그 클래스의 속성에 @ApiProperty()가 있는지
UpdateUserDto만 비어 있음PartialType을 @nestjs/swagger에서 가져왔는지
Try it out이 404문서의 경로에 /v1이 있는지. /api-json의 paths에서 확인합니다
Authorize를 했는데도 401addBearerAuth()와 @ApiBearerAuth()의 이름이 같은지, 입력한 값이 demo-token인지

더 깊이: CLI 플러그인은 컴파일 단계에서 무엇을 채울까

@ApiProperty()를 필드마다 붙여야 하는 까닭은 TypeScript의 메타데이터 반영 기능에 한계가 있기 때문입니다. CLI 플러그인 문서의 설명처럼, 실행 시점의 메타데이터만으로는 클래스에 어떤 속성이 있는지, 그 속성이 선택인지 필수인지 알 수 없습니다. 그래서 nest-cli.json의 compilerOptions.plugins에 @nestjs/swagger를 넣으면, Nest CLI가 컴파일할 때 소스의 구조를 읽어 DTO 속성마다 @ApiProperty()에 해당하는 메타데이터를 채웁니다. name?: string의 물음표로 required: false를, 타입으로 type이나 enum을 정하고 배열도 알아보며, 초기값은 default로 남깁니다.

이 플러그인이 분석하는 파일은 이름이 .dto.ts나 .entity.ts로 끝나는 것뿐입니다. 이 글의 users-response.model.ts는 어느 쪽에도 맞지 않으므로, 플러그인을 켜도 dtoFileNameSuffix 옵션을 바꾸지 않으면 지금처럼 데코레이터를 직접 붙여야 합니다. 또 플러그인은 Nest CLI의 컴파일 과정에 끼어드는 것이라서 소스를 따로 컴파일하는 도구에는 적용되지 않습니다. 예를 들어 ts-jest는 소스를 메모리에서 바로 컴파일하므로 Jest 설정에 별도의 변환기를 연결해야 하고, SWC 빌더는 --type-check를 켜야 플러그인을 쓸 수 있습니다.

Express 대신 Fastify 어댑터를 쓴다면 Swagger UI를 띄우는 데 @fastify/static을 추가로 설치합니다.


정리

  • @nestjs/swagger는 DocumentBuilder의 설정, 컨트롤러의 경로 정보, DTO와 응답 모델의 스키마를 모아 OpenAPI 문서를 만들고, /api에 Swagger UI를, /api-json과 /api-yaml에 명세를 제공합니다.
  • 클래스의 속성은 @ApiProperty()를 붙여야 문서에 나오고, 응답의 모양을 그리려면 인터페이스가 아닌 클래스가 필요합니다.
  • @ApiProperty(), @ApiResponse(), @ApiBearerAuth()는 문서만 바꿉니다. 검증은 파이프가, 접근 제어는 가드가 합니다.
  • 문서를 고친 뒤에는 Try it out이나 curl로 실제 요청·응답과 비교합니다.

연습 문제

1. 문서의 길이 제한만 고치면

CreateUserDto의 name에서 @ApiProperty()의 maxLength를 80에서 40으로 고치고 @Length(1, 80)은 그대로 두었습니다. 60글자 이름으로 생성 요청을 보내면 어떻게 되나요? 40글자 제한을 실제로 적용하려면 무엇을 고쳐야 하나요?

해설 보기

201로 생성됩니다. 문서의 maxLength는 검증 규칙을 바꾸지 않으므로 60글자는 @Length(1, 80)을 통과합니다. 문서는 40글자까지라고 말하고 서버는 80글자까지 받는, 어긋난 상태가 됩니다.

실제로 적용하려면 @Length(1, 40)으로 고치고 60글자 요청이 400이 되는지 확인합니다. 다만 이미 41자에서 80자 사이의 이름을 보내던 클라이언트가 있다면 그 요청이 갑자기 거부되므로, 다음 글에서 다루는 "깨지는 변경"에 해당합니다. 확인한 뒤에는 두 길이 제한을 모두 80으로 되돌립니다.

2. 문서를 미리 만들면

documentFactory 대신 const document = SwaggerModule.createDocument(app, config);를 app.enableVersioning()보다 앞줄에서 호출하고, SwaggerModule.setup('api', app, document)로 넘기도록 바꾸었습니다. Swagger UI에서 목록 조회의 Try it out을 실행하면 어떤 일이 생길까요?

해설 보기

공식 문서의 안내대로, 문서를 즉시 만들 때 버전 설정이 아직 적용되지 않았다면 생성된 paths에 버전 접두사가 빠집니다. 문서에는 /users가 표시되지만 실제 경로는 /v1/users이므로 Try it out으로 보낸 요청은 404가 됩니다.

app.enableVersioning()을 먼저 호출하거나, 본문처럼 함수로 감싸 문서가 처음 요청될 때 만들어지게 하면 해결됩니다.

3. Authorize를 했는데도 401이 나오는 코드 고치기

동료가 수정 핸들러도 보호하려고 다음처럼 고쳤습니다. Swagger UI에서 Authorize에 demo-token을 입력했는데, 삭제는 204인데 수정만 401입니다. 원인을 찾아 고치세요.

src/users/users.controller.ts (고칠 코드)
  @Patch(':id')
  @UseGuards(DemoTokenGuard)
  @ApiBearerAuth()
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateUserDto,
  ): UserResponseDto {
    // 그대로
  }
해설 보기

@ApiBearerAuth()에 이름을 주지 않으면 기본값 bearer가 쓰입니다. 그러면 이 엔드포인트는 문서에 정의되지 않은 bearer라는 보안 방식을 요구하게 됩니다. Authorize에 입력한 값은 access-token이라는 이름으로 저장되므로 수정 요청에는 Authorization 헤더가 실리지 않고, 가드가 401로 거부합니다.

@ApiBearerAuth('access-token')으로 고쳐 addBearerAuth()에 준 이름과 맞춥니다. 가드는 처음부터 제대로 동작하고 있었고, 틀린 것은 문서 쪽이었습니다. curl에 헤더를 직접 붙이면 고치기 전에도 200이 나오는 것으로 확인할 수 있습니다. 확인한 뒤에는 수정 핸들러의 두 데코레이터를 지워, 삭제만 토큰을 요구하는 상태로 되돌립니다.

4. 나머지 엔드포인트 문서 완성하기

단일 조회, 수정, 삭제에도 문서를 붙여 다섯 엔드포인트의 문서를 완성하세요.

  • 엔드포인트마다 @ApiOperation()으로 요약을 붙입니다.
  • 단일 조회와 수정의 성공 응답에는 UserResponseModel 스키마가 보여야 합니다.
  • 각 엔드포인트가 실제로 낼 수 있는 실패(400, 401, 404, 409)를 빠짐없이 적습니다. 낼 수 없는 상태 코드는 적지 않습니다.
해설 보기

핸들러의 본문은 5장 첫 글과 앞 글에서 만든 그대로이고, 데코레이터만 늘었습니다. 완성한 컨트롤러 전체입니다.

src/users/users.controller.ts
import {
  Body,
  ConflictException,
  Controller,
  Delete,
  Get,
  HttpCode,
  HttpStatus,
  NotFoundException,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Query,
  Res,
  UseGuards,
} from '@nestjs/common';
import {
  ApiBearerAuth,
  ApiOperation,
  ApiQuery,
  ApiResponse,
  ApiTags,
} from '@nestjs/swagger';
import type { Response } from 'express';
import { DemoTokenGuard } from '../common/demo-token.guard';
import { CreateUserDto } from './dto/create-user.dto';
import { ListUsersQueryDto } from './dto/list-users-query.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import {
  UserResponseDto,
  type UsersPageResponse,
} from './dto/user-response.dto';
import {
  UserResponseModel,
  UsersPageResponseModel,
} from './dto/users-response.model';
import { EmailAlreadyUsedError, UsersService } from './users.service';

@ApiTags('users')
@Controller({ path: 'users', version: '1' })
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  @ApiOperation({ summary: '사용자 목록 조회' })
  @ApiQuery({
    name: 'page',
    required: false,
    schema: { type: 'integer', minimum: 1, default: 1 },
  })
  @ApiQuery({
    name: 'limit',
    required: false,
    schema: { type: 'integer', minimum: 1, maximum: 100, default: 20 },
  })
  @ApiResponse({
    status: 200,
    description: '빈 목록도 같은 구조입니다.',
    type: UsersPageResponseModel,
  })
  @ApiResponse({ status: 400, description: 'page 또는 limit 검증 실패' })
  findAll(@Query() query: ListUsersQueryDto): UsersPageResponse {
    const result = this.usersService.findAll(query.page, query.limit);

    return {
      items: result.items.map(UserResponseDto.from),
      page: query.page,
      limit: query.limit,
      total: result.total,
    };
  }

  @Get(':id')
  @ApiOperation({ summary: '사용자 한 명 조회' })
  @ApiResponse({ status: 200, type: UserResponseModel })
  @ApiResponse({ status: 400, description: 'id가 숫자가 아님' })
  @ApiResponse({ status: 404, description: '없는 사용자' })
  findOne(@Param('id', ParseIntPipe) id: number): UserResponseDto {
    const user = this.usersService.findOne(id);
    if (!user) throw new NotFoundException('User not found');

    return UserResponseDto.from(user);
  }

  @Post()
  @ApiOperation({ summary: '사용자 생성' })
  @ApiResponse({
    status: 201,
    description: 'Location 헤더에 새 사용자의 주소가 담깁니다.',
    type: UserResponseModel,
  })
  @ApiResponse({ status: 400, description: '본문 검증 실패' })
  @ApiResponse({ status: 409, description: '이미 쓰는 이메일' })
  create(
    @Body() dto: CreateUserDto,
    @Res({ passthrough: true }) response: Response,
  ): UserResponseDto {
    try {
      const user = this.usersService.create(dto);
      response.setHeader('Location', '/v1/users/' + user.id);
      return UserResponseDto.from(user);
    } catch (error) {
      this.rethrowConflict(error);
    }
  }

  @Patch(':id')
  @ApiOperation({ summary: '사용자 일부 수정' })
  @ApiResponse({ status: 200, type: UserResponseModel })
  @ApiResponse({ status: 400, description: 'id 또는 본문 검증 실패' })
  @ApiResponse({ status: 404, description: '없는 사용자' })
  @ApiResponse({ status: 409, description: '이미 쓰는 이메일' })
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() dto: UpdateUserDto,
  ): UserResponseDto {
    try {
      const user = this.usersService.update(id, dto);
      if (!user) throw new NotFoundException('User not found');

      return UserResponseDto.from(user);
    } catch (error) {
      this.rethrowConflict(error);
    }
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  @UseGuards(DemoTokenGuard)
  @ApiBearerAuth('access-token')
  @ApiOperation({ summary: '사용자 삭제' })
  @ApiResponse({ status: 204, description: '응답 본문 없음' })
  @ApiResponse({ status: 400, description: 'id가 숫자가 아님' })
  @ApiResponse({ status: 401, description: '토큰이 없거나 틀림' })
  @ApiResponse({ status: 404, description: '없는 사용자' })
  remove(@Param('id', ParseIntPipe) id: number): void {
    if (!this.usersService.remove(id)) {
      throw new NotFoundException('User not found');
    }
  }

  private rethrowConflict(error: unknown): never {
    if (error instanceof EmailAlreadyUsedError) {
      throw new ConflictException('Email already in use');
    }
    throw error;
  }
}

확인은 문서와 실제 응답을 짝지어 합니다. Swagger UI에서 단일 조회에 id 999를 넣어 실행하면 404가, 수정의 id에 1을 넣고 {"email":"[email protected]"}을 보내면 409가 나오고, 두 상태 코드가 모두 문서의 응답 목록에 있어야 합니다. 조회에는 409를 적지 않았습니다. 조회는 이메일 규칙을 건드리지 않아 409를 낼 수 없기 때문입니다. 첫 글의 연습 문제에서 만든 PUT을 남겨 두었다면 수정과 같은 응답 목록을 붙입니다.

다음 글 버전 관리와 API 진화 전략에서는 이렇게 문서로 약속한 API를 이미 쓰고 있는 클라이언트를 깨뜨리지 않으면서 바꾸는 방법을 다룹니다.