API·Swagger 실무 가이드 · Part 3

Swagger / OpenAPI 실무 심화

Swagger UI를 보여주는 데서 끝나지 않고 실제 API 계약을 유지하는 OpenAPI 작성법

작성 기준2026년 7월

이 파트에서 다루는 내용

CH 08 OpenAPI 핵심 개념CH 09 Express + Swagger 연동CH 10 요청/응답 스키마 작성법CH 11 인증(JWT) 문서화하기CH 12 버전 관리와 변경 이력
01

OpenAPI 문서는 세 축으로 읽습니다

OpenAPI 문서는 보통 paths, components/schemas, components/securitySchemes를 중심으로 읽습니다. paths는 어떤 URL과 메서드가 있는지, schemas는 재사용 가능한 데이터 구조가 무엇인지, securitySchemes는 인증 방식을 정의합니다.

OpenAPI 기본 구조yaml
openapi: 3.0.0
info:
  title: PMS API
  version: 1.0.0
paths:
  /products:
    get:
      summary: 상품 목록 조회
      responses:
        '200':
          description: 성공
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Product'
components:
  schemas:
    Product:
      type: object
      properties:
        id: { type: integer }
        name: { type: string }

paths는 엔드포인트, components는 재사용 가능한 계약입니다.

02

Express에서는 주석 기반으로 Swagger UI를 붙일 수 있습니다

Node.js/Express 환경에서는 swagger-jsdoc으로 라우트 주석에서 스펙을 생성하고, swagger-ui-express로 그 스펙을 웹 UI로 띄우는 구성이 흔합니다.

다만 주석이 있어도 리뷰 없이 방치하면 문서는 다시 어긋납니다. 스펙 변경을 PR에서 확인하는 습관이 함께 필요합니다.

설치bash
npm install swagger-jsdoc swagger-ui-express
swagger.jsjs
const swaggerJsdoc = require("swagger-jsdoc");

const options = {
  definition: {
    openapi: "3.0.0",
    info: { title: "PMS API", version: "1.0.0" },
    servers: [{ url: "http://localhost:3000" }],
  },
  apis: ["./routes/*.js"],
};

module.exports = swaggerJsdoc(options);
app.jsjs
const swaggerUi = require("swagger-ui-express");
const swaggerSpec = require("./swagger");

app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpec));

/api-docs에서 Swagger UI를 확인합니다.

03

성공 응답과 에러 응답을 함께 적습니다

실무에서 가장 자주 빠뜨리는 부분은 에러 응답입니다. 성공 케이스만 적으면 프론트는 실패 시 어떤 구조를 받을지 알 수 없습니다.

단건 조회 스키마 예시jsdoc
/**
 * @swagger
 * /products/{id}:
 *   get:
 *     summary: 상품 단건 조회
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema: { type: integer }
 *     responses:
 *       200:
 *         description: 조회 성공
 *       404:
 *         description: 상품 없음
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 error: { type: string, example: "Product not found" }
 */
작성 우선순위

모든 상태 코드를 한 번에 다 쓰려 하지 말고, 클라이언트가 실제로 분기 처리할 성공 응답과 대표 에러 응답부터 정확히 적습니다.

04

JWT 인증도 스펙에 포함합니다

JWT 기반 인증을 쓰는 프로젝트라면 securitySchemes를 정의해야 Swagger UI에서 Authorize 버튼으로 토큰을 넣고 인증 API를 직접 테스트할 수 있습니다.

Bearer 인증 스킴yaml
components:
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

paths:
  /products:
    post:
      security:
        - bearerAuth: []
      summary: 상품 등록 (인증 필요)
05

버전과 변경 이력은 API 문서의 일부입니다

  • URL 버저닝은 /v1/products, /v2/products처럼 가장 명확하게 드러나는 방식입니다.
  • 헤더 버저닝은 URL은 깔끔하지만 호출자가 알아차리기 어려워 문서화 품질이 더 중요합니다.
  • OpenAPI의 info.version과 변경 이력을 함께 관리하면 변경 내용을 코드 검색 없이 확인할 수 있습니다.
  • 필드 삭제, 필수 여부 변경, 타입 변경은 기존 클라이언트를 깨뜨릴 수 있으므로 별도 공지합니다.
체크

이 파트 완료 기준