← 中文资源

简体中文版本

How to Implement API Versioning with URL Path

Version an API by embedding the version in the URL path, with backward-compatible defaults, deprecation headers, and sunset tracking.

阅读英文原文

引言

API versioning lets you evolve the API without breaking existing clients. The URL path approach embeds the version in the path, like /v1/users and /v2/users, so each version is a distinct set of routes. This is the most visible and cache-friendly approach: clients see the version in the URL, and caches key on the full path. This guide implements path-based versioning with deprecation headers and sunset tracking. 本文将逐步拆解设计与实现,帮助你在生产环境中安全落地。

问题

Without versioning, a breaking change breaks every client. With versioning, you can ship v2 with the new shape while v1 keeps working. The challenge is managing the lifecycle: knowing when to deprecate, how to communicate the migration, and when to sunset. A good versioning strategy makes the version explicit, the deprecation visible, and the sunset data-driven. 理解问题的全貌是设计正确方案的前提。

设计决策

Each version is mounted under a prefix: app.use(‘/v1’, v1Routes) and app.use(‘/v2’, v2Routes). The routes share core logic but use version-specific adapters for response shapes. When v2 ships, v1 gets Deprecation and Sunset headers pointing to the migration guide. The server logs the version and endpoint for every request, so a dashboard shows v1 usage over time. When v1 usage drops below a threshold, the routes are removed and a 410 Gone response replaces them. 以下代码展示了核心结构:

app.use('/v1', v1Router);
app.use('/v2', v2Router);
// Deprecation middleware on v1
v1Router.use((req, res, next) => {
  res.set('Deprecation', 'true');
  res.set('Sunset', '2026-12-31');
  res.set('Link', '</v2/users>; rel="successor-version"');
  next();
});

实现

The v1 and v2 routers share the same handlers but transform the response. A v1 adapter wraps the core handler and maps the v2 response to the v1 shape, stripping new fields or renaming old ones. The deprecation middleware runs on v1 and sets the headers. The usage log records the version, endpoint, and status code; a scheduled job aggregates the data and alerts when v1 usage drops below the sunset threshold. On sunset, the v1 router is replaced with a 410 handler that links to the migration guide. 实现时需注意性能与正确性的平衡:

// v1 adapter: strip v2-only fields
function v1Adapter(handler) {
  return async (req, res) => {
    const result = await handler(req);
    const { newField, ...v1Shape } = result;
    res.json(v1Shape);
  };
}

测试边界

Test that /v1/users returns the v1 shape and /v2/users returns the v2 shape. Test that v1 responses include Deprecation and Sunset headers. Test that a request to a sunset version returns 410 with a Link to the migration guide. Test that the usage log records the correct version for each request. Test that v1 and v2 can coexist without interference. 测试应覆盖正常路径与异常路径,确保系统在边界条件下行为正确。

常见陷阱

Avoid creating a new version for non-breaking changes; add fields or endpoints to the current version instead. Avoid supporting too many versions; each version is maintenance cost. Avoid sunsetting without notice; announce the sunset date in headers and docs well in advance. Avoid versioning by query parameter or header; it breaks caching and is less discoverable. Avoid copying v1 to v2 without refactoring; v2 should fix design mistakes, not repeat them. 避开这些陷阱可以减少生产事故。

结论

URL path versioning makes the API version explicit, cache-friendly, and easy to route. Mount each version under a prefix, share core logic with version-specific adapters, and add deprecation headers when a version is superseded. Track usage to decide when to sunset, and replace sunset routes with a 410 that links to the migration guide. The result is an API that evolves without breaking clients. 按照本文的方法,你可以构建出既安全又高效的解决方案。

Sources: API versioning, RFC 8594 Sunset.