Advanced

Claude Code로 API 버전 관리 전략 설계 및 구현하기

Claude Code를 사용한 API 버전 관리 전략 설계 및 구현 방법을 알아봅니다. 실용적인 팁과 코드 예시를 포함합니다.

API 버전 관리의 중요성

API의 브레이킹 체인지는 클라이언트 애플리케이션에 큰 영향을 미칩니다. Claude Code를 활용하면 버전 관리 전략 설계부터 구현까지 일관되게 진행할 수 있습니다.

3가지 버전 관리 방식

방식예시장점단점
URL 경로/api/v1/users명확하고 이해하기 쉬움URL이 변경됨
헤더API-Version: 1URL이 깔끔함발견하기 어려움
AcceptAccept: application/vnd.app.v1+jsonHTTP 표준 준수복잡해지기 쉬움

URL 경로 방식의 구현

가장 일반적이고 이해하기 쉬운 방식입니다.

import express from "express";

const app = express();

// 버전별 라우터
import v1Router from "./routes/v1";
import v2Router from "./routes/v2";

app.use("/api/v1", v1Router);
app.use("/api/v2", v2Router);

// routes/v1/users.ts
const v1Router = express.Router();

v1Router.get("/users", async (req, res) => {
  const users = await prisma.user.findMany();
  // v1 응답 형식
  res.json({
    data: users.map((u) => ({
      id: u.id,
      name: u.name,
      email: u.email,
    })),
  });
});

// routes/v2/users.ts
const v2Router = express.Router();

v2Router.get("/users", async (req, res) => {
  const users = await prisma.user.findMany({
    include: { profile: true },
  });
  // v2 응답 형식 (페이지네이션 추가)
  res.json({
    data: users.map((u) => ({
      id: u.id,
      fullName: u.name,
      email: u.email,
      profile: u.profile,
    })),
    pagination: {
      total: users.length,
      page: 1,
      perPage: 20,
    },
  });
});

헤더 방식의 구현

function versionMiddleware(
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) {
  const version = req.headers["api-version"] || "1";
  req.apiVersion = parseInt(version as string, 10);

  // 지원되는 버전인지 확인
  const supportedVersions = [1, 2, 3];
  if (!supportedVersions.includes(req.apiVersion)) {
    return res.status(400).json({
      error: `Unsupported API version: ${version}`,
      supportedVersions,
    });
  }

  // 지원 종료 예정 버전의 경고 헤더
  if (req.apiVersion < 2) {
    res.set("Deprecation", "true");
    res.set("Sunset", "2026-06-01");
    res.set(
      "Link",
      '<https://api.example.com/docs/migration>; rel="deprecation"'
    );
  }

  next();
}

app.use("/api", versionMiddleware);

app.get("/api/users", async (req, res) => {
  switch (req.apiVersion) {
    case 1:
      return handleUsersV1(req, res);
    case 2:
      return handleUsersV2(req, res);
    default:
      return handleUsersV2(req, res);
  }
});

응답 변환 패턴

버전 간 차이를 변환 레이어에서 흡수하는 설계입니다.

type UserV1 = {
  id: string;
  name: string;
  email: string;
};

type UserV2 = {
  id: string;
  fullName: string;
  emailAddress: string;
  createdAt: string;
};

const transformers = {
  1: (user: DBUser): UserV1 => ({
    id: user.id,
    name: user.name,
    email: user.email,
  }),
  2: (user: DBUser): UserV2 => ({
    id: user.id,
    fullName: user.name,
    emailAddress: user.email,
    createdAt: user.createdAt.toISOString(),
  }),
};

function createVersionedHandler<T>(
  fetcher: (req: express.Request) => Promise<T[]>,
  transformerMap: Record<number, (item: T) => unknown>
) {
  return async (req: express.Request, res: express.Response) => {
    const data = await fetcher(req);
    const transform = transformerMap[req.apiVersion];
    res.json({ data: data.map(transform) });
  };
}

지원 종료와 마이그레이션 지원

function deprecationNotice(
  sunsetDate: string,
  migrationGuide: string
) {
  return (
    req: express.Request,
    res: express.Response,
    next: express.NextFunction
  ) => {
    res.set("Deprecation", "true");
    res.set("Sunset", sunsetDate);
    res.set("Link", `<${migrationGuide}>; rel="deprecation"`);

    console.warn(
      `Deprecated API v${req.apiVersion} accessed: ${req.path}`
    );

    next();
  };
}

// v1은 2026년 6월에 폐기 예정
app.use(
  "/api/v1",
  deprecationNotice(
    "2026-06-01",
    "https://docs.example.com/migration/v1-to-v2"
  ),
  v1Router
);

Claude Code 구현 프롬프트

API 버전 관리 도입을 Claude Code에 요청할 때의 프롬프트 예시입니다. API 설계 기본은 Claude Code 시작 가이드를, 에러 처리는 에러 바운더리 설계를 참고하세요.

기존 REST API에 버전 관리를 도입해줘.
- URL 경로 방식 (/api/v1, /api/v2)
- v1은 현재 API를 그대로 유지
- v2에서 응답 형식 통일 (pagination 추가)
- v1에 지원 종료 헤더도 설정해줘
- 마이그레이션 가이드 문서도 작성해줘

API 버전 관리 모범 사례에 대해서는 Microsoft REST API Guidelines도 참고가 됩니다. Claude Code의 활용법은 공식 문서를 확인하세요.

정리

API 버전 관리는 장기 운영에 필수적인 설계입니다. Claude Code로 기존 코드 구조를 이해한 후 버전 관리를 도입하면, 기존 클라이언트에 대한 영향을 최소화하면서 API를 발전시켜 나갈 수 있습니다.

#Claude Code #API design #versioning #REST API #TypeScript