← 中文资源

简体中文版本

面向长期系统的 API 设计原则

设计能存活多年的 API:显式版本管理、一致分页、幂等安全、清晰错误,以及用于可发现性的超媒体链接。

阅读英文原文

引言

长期 API 的成本不在第一次发布,而在多年里不断演进的客户端、数据和契约。设计目标是让兼容变更容易、破坏变更可见、失败可预测。

版本管理

把破坏性变更放进新的显式版本,而不是在同一路径下悄悄改变语义。版本应在 URL 或媒体类型中可识别,旧版本要有弃用时间线和迁移文档。能用增量字段解决时不要发新版本,避免版本爆炸。

分页与幂等

所有列表使用同一种分页方式,并给出稳定排序键;游标分页比 offset 更适合大表和并发写入。对创建、支付等操作支持幂等键,让客户端在超时后安全重试,服务端返回同一结果而不是重复执行。

错误与可发现性

错误响应应包含稳定的机器可读 code、人类可读消息和可操作的细节,并携带 request id 以便排查。用链接暴露相关资源和可用操作,让客户端不必硬编码 URL 结构;但不要为了 HATEOAS 而牺牲简单性。

一致性与契约

命名、日期格式、空值和错误形状应全站一致。把 OpenAPI 作为契约纳入评审和 CI,明确限流与配额响应头。一致性比任何单条规则都重要:客户端会依赖模式,而不是文档。

代码示例

// Route by version; the old version stays available and deprecated.
router.use("/v1", v1Routes);   // deprecated, still served
router.use("/v2", v2Routes);   // current
// Cursor pagination with a consistent envelope.
interface Page<T> {
  data: T[];
  nextCursor: string | null; // null when there is no more data
  hasMore: boolean;
}

async function listUsers(req: Request): Promise<Page<User>> {
  const limit = Math.min(Number(req.query.limit ?? 50), 100); // cap the page size
  const cursor = req.query.after ? decodeCursor(req.query.after) : null;
  const rows = await db.users.findMany({ take: limit + 1, skip: cursor ? 1 : 0, cursor: cursor ?? undefined, orderBy: { id: "asc" } });
  const hasMore = rows.length > limit;
  const data = hasMore ? rows.slice(0, limit) : rows;
  return { data, nextCursor: hasMore ? encodeCursor(data[data.length - 1].id) : null, hasMore };
}
router.post("/charges", async (req, res) => {
  const key = req.headers["idempotency-key"] as string | undefined;
  if (!key) return res.status(400).json({ error: "Idempotency-Key required" });
  const existing = await idempotency.get(key);
  if (existing) return res.status(existing.status).json(existing.body); // replay the original result
  try {
    const result = await createCharge(req.body);
    await idempotency.set(key, { status: 201, body: result }, { ttl: 86400 });
    res.status(201).json(result);
  } catch (err) {
    await idempotency.set(key, { status: 500, body: { error: "failed" } }, { ttl: 600 });
    throw err;
  }
});
// Consistent error envelope.
interface ApiError {
  code: string;          // machine-readable, e.g. "validation_failed"
  message: string;       // human-readable
  details?: Array<{ field: string; code: string; message: string }>;
  requestId: string;     // for support correlation
}

// 422 with field-level details.
res.status(422).json({
  code: "validation_failed",
  message: "The request was invalid.",
  details: [{ field: "email", code: "already_taken", message: "That email is already registered." }],
  requestId: req.id,
});
function userResource(user: User, req: Request) {
  return {
    ...user,
    links: {
      self: `${req.baseUrl}/users/${user.id}`,
      update: { href: `${req.baseUrl}/users/${user.id}`, method: "PATCH" },
      deactivate: { href: `${req.baseUrl}/users/${user.id}`, method: "DELETE" },
    },
  };
}
// A sliding-window rate limiter backed by Redis.
async function rateLimit(key: string, limit: number, windowMs: number): Promise<boolean> {
  const now = Date.now();
  const member = `${now}:${crypto.randomUUID()}`;
  const tx = redis.multi();
  tx.zremrangebyscore(key, 0, now - windowMs); // drop entries outside the window
  tx.zadd(key, now, member);
  tx.zcard(key); // count entries in the window
  tx.pexpire(key, windowMs);
  const results = await tx.exec();
  const count = results[2] as number;
  return count <= limit; // false -> 429 Too Many Requests
}
// Generate the OpenAPI spec from the Zod schemas that define the routes.
import { createDocument } from "zod-openapi";
const doc = createDocument({
  openapi: "3.1.0",
  info: { title: "Example API", version: "1.0.0" },
  paths: {
    "/users/{id}": {
      get: {
        parameters: [{ name: "id", in: "path", required: true, schema: { type: "string" } }],
        responses: { "200": { description: "A user", content: { "application/json": { schema: UserSchema } } } },
      },
    },
  },
});