본문 바로가기
Backend2025년 11월 5일6분 읽기

Swagger/OpenAPI 3.1 API 문서 자동화

YS
김영삼
조회 695

OpenAPI 3.1 소개

OpenAPI Specification(OAS)은 REST API를 표준화된 형식으로 기술하는 스펙입니다. 3.1 버전부터 JSON Schema와 완전 호환되어 스키마 재사용이 크게 개선되었습니다.

기본 OpenAPI 문서 구조

openapi: "3.1.0"
info:
  title: 기술 노트 API
  description: 기술 노트 CRUD API
  version: "1.0.0"

servers:
  - url: https://api.example.com/v1
    description: Production
  - url: http://localhost:3000/api/v1
    description: Development

paths:
  /posts:
    get:
      summary: 게시글 목록 조회
      tags: [Posts]
      parameters:
        - name: page
          in: query
          schema:
            type: integer
            default: 1
        - 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:
                      type: object
                  total:
                    type: integer

Express + Swagger UI 통합

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

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

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc, {
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: 'API 문서',
  swaggerOptions: {
    persistAuthorization: true,
    filter: true,
  },
}));

app.get('/api-docs.json', (req, res) => {
  res.json(swaggerDoc);
});

코드에서 자동 생성 (swagger-jsdoc)

const swaggerJsdoc = require('swagger-jsdoc');

const options = {
  definition: {
    openapi: '3.1.0',
    info: { title: 'My API', version: '1.0.0' },
  },
  apis: ['./routes/*.js'],
};

const spec = swaggerJsdoc(options);

/**
 * @openapi
 * /api/users/{id}:
 *   get:
 *     summary: 사용자 조회
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *     responses:
 *       200:
 *         description: 성공
 */
app.get('/api/users/:id', getUser);

OpenAPI 3.0 vs 3.1 변경점

항목3.03.1
JSON Schema서브셋완전 호환
nullablenullable: truetype: ["string", "null"]
웹훅미지원webhooks 키워드 지원
exclusiveMinimumboolean숫자값
  • OpenAPI 스펙은 API 설계 단계에서 먼저 작성하는 Design-First 접근을 권장합니다
  • 코드 생성 도구(openapi-generator)로 클라이언트 SDK를 자동 생성할 수 있습니다
  • 스키마를 Zod/TypeBox와 공유하여 런타임 검증과 문서를 동기화합니다
  • CI/CD에서 spectral 같은 린터로 스펙 품질을 자동 검증합니다

OpenAPI 3.1은 API의 설계, 문서화, 테스트, 코드 생성을 하나의 스펙으로 통합합니다. API 개발의 효율성과 협업 품질을 동시에 높이는 핵심 도구입니다.

댓글 0

아직 댓글이 없습니다.
Ctrl+Enter로 등록