Swagger
스웨거
API 문서화 도구. OpenAPI 스펙. 자동 문서 생성.
스웨거
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.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: []
// 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');
});