Advanced

Designing and Implementing API Versioning Strategies with Claude Code

Learn about designing and implementing api versioning strategies using Claude Code. Practical tips and code examples included.

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の活用法は公式ドキュメントを確認してください。

Summary

APIバージョニングは長期運用に不可欠な設計です。Claude Codeで既存コードの構造を理解した上でバージョニングを導入すれば、既存クライアントへの影響を最小限に抑えながら進化させていけます。

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