🔧 DevOps

Swagger

스웨거

API 문서화 도구. OpenAPI 스펙. 자동 문서 생성.

상세 설명

Swagger는 RESTful API를 설계, 문서화, 테스트하기 위한 도구 모음입니다. 현재는 OpenAPI Specification(OAS)이라는 이름으로 표준화되었으며, API의 구조를 YAML 또는 JSON으로 정의하여 자동으로 문서와 클라이언트 SDK를 생성할 수 있습니다.

Swagger/OpenAPI 생태계는 크게 세 가지로 구성됩니다: Swagger Editor(스펙 작성), Swagger UI(인터랙티브 문서), Swagger Codegen(코드 생성). API-First 설계 방식에서는 코드 작성 전에 OpenAPI 스펙을 먼저 정의하고, 이를 기반으로 서버 스텁과 클라이언트 SDK를 자동 생성합니다. 프론트엔드와 백엔드 팀이 병렬로 개발할 수 있어 생산성이 크게 향상됩니다.

코드 예제

OpenAPI 3.0 스펙 예제

# openapi.yaml
openapi: 3.0.3
info:
  title: E-Commerce API
  description: 전자상거래 플랫폼 REST API
  version: 1.0.0
  contact:
    name: API Support
    email: api@example.com
servers:
  - url: https://api.example.com/v1
    description: Production
  - url: https://staging-api.example.com/v1
    description: Staging

paths:
  /products:
    get:
      summary: 상품 목록 조회
      tags:
        - Products
      parameters:
        - name: category
          in: query
          schema:
            type: string
          description: 카테고리 필터
        - name: limit
          in: query
          schema:
            type: integer
            default: 20
            maximum: 100
      responses:
        '200':
          description: 성공
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    items:
                      $ref: '#/components/schemas/Product'
                  pagination:
                    $ref: '#/components/schemas/Pagination'

  /products/{productId}:
    get:
      summary: 상품 상세 조회
      tags:
        - Products
      parameters:
        - name: productId
          in: path
          required: true
          schema:
            type: string
            format: uuid
      responses:
        '200':
          description: 성공
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Product'
        '404':
          $ref: '#/components/responses/NotFound'

components:
  schemas:
    Product:
      type: object
      required:
        - id
        - name
        - price
      properties:
        id:
          type: string
          format: uuid
        name:
          type: string
          minLength: 1
          maxLength: 200
        price:
          type: number
          format: float
          minimum: 0
        description:
          type: string
        category:
          type: string
        createdAt:
          type: string
          format: date-time

    Pagination:
      type: object
      properties:
        total:
          type: integer
        page:
          type: integer
        limit:
          type: integer

  responses:
    NotFound:
      description: 리소스를 찾을 수 없음
      content:
        application/json:
          schema:
            type: object
            properties:
              error:
                type: string
              message:
                type: string

  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

security:
  - bearerAuth: []

Express.js에서 Swagger UI 설정

// app.js
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

const app = express();
const swaggerDocument = YAML.load('./openapi.yaml');

// Swagger UI 설정
const swaggerOptions = {
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: "E-Commerce API Docs",
  swaggerOptions: {
    persistAuthorization: true,
    displayRequestDuration: true,
  }
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, swaggerOptions));

// API 엔드포인트
app.get('/products', (req, res) => {
  // OpenAPI 스펙에 정의된 대로 응답
  res.json({
    data: [...],
    pagination: { total: 100, page: 1, limit: 20 }
  });
});

app.listen(3000, () => {
  console.log('API 서버 실행 중: http://localhost:3000');
  console.log('API 문서: http://localhost:3000/api-docs');
});

실무 대화

프론트엔드 개발자

"백엔드 API 개발이 끝나야 프론트 작업을 시작할 수 있어서 일정이 촉박해요."

백엔드 개발자

"OpenAPI 스펙을 먼저 작성해서 공유할게요. Swagger UI로 목업 응답을 제공하면 병렬로 개발할 수 있어요."

프론트엔드 개발자

"타입 정의도 수동으로 해야 하나요? API 응답 타입이 바뀌면 놓치기 쉬운데..."

백엔드 개발자

"openapi-typescript 같은 도구로 OpenAPI 스펙에서 TypeScript 타입을 자동 생성할 수 있어요. 스펙이 변경되면 타입도 자동 업데이트되니까 안전하죠."

QA 엔지니어

"Swagger UI에서 직접 API 호출 테스트도 가능한가요?"

백엔드 개발자

"네, 'Try it out' 버튼으로 바로 테스트할 수 있어요. 인증 토큰도 설정해두면 편리합니다."

주의사항

  • 스펙과 구현 동기화: OpenAPI 스펙과 실제 API 구현이 다르면 혼란이 발생합니다. 코드에서 스펙을 자동 생성하거나, 스펙 기반 검증 미들웨어를 사용하세요.
  • 보안 정보 노출: 프로덕션 Swagger UI에서 내부 API나 민감한 엔드포인트가 노출되지 않도록 주의하세요. 필요시 접근 제한을 설정하세요.
  • 버전 관리: API 버전이 변경될 때 OpenAPI 스펙도 함께 버전 관리하세요. /v1, /v2 등 경로에 버전을 명시하는 것이 좋습니다.
  • 과도한 문서화: 모든 세부사항을 스펙에 담으려 하지 마세요. 핵심 계약(요청/응답 스키마)에 집중하세요.
  • 예제 데이터: example 필드에 실제적인 예제 데이터를 제공하면 문서 가독성이 크게 향상됩니다.

더 배우기