API 要升级又不能破坏老客户端,版本怎么管?用 URL 前缀还是请求头?怎么提示调用方老版本要下线?这篇把两种做法都写出来,逐个验证每种请求会得到什么。
/v1/users/1 → 200 {"id":1,"name":"Ann Lee"}
/v2/users/1 → 200 {"email":"ann@x.test","first_name":"Ann","id":1,"last_name":"Lee"}
/v3/users/1 → 404 (HTML 404 页面)
url_for 生成的地址: /v1/users/1 /v2/users/1
路由表:
['GET'] /v1/users/<int:i> → v1.u1
['GET'] /v2/users/<int:i> → v2.u2
['GET'] /health → health上一篇:API 分页;下一篇:RESTful URL 设计。
/v1/users/1 Deprecation=true Sunset=Wed, 31 Dec 2026 23:59:59 GMT Link=</v2/users>; rel="successor-version" /v2/users/1 Deprecation=None Sunset=None Link=None /health Deprecation=None Sunset=None Link=None v1 的 404 响应有没有这些头: true
Accept: …v1+json → 200 application/vnd.app.v1+json {"id":1,"name":"Ann Lee"}
Accept: …v2+json → 200 application/vnd.app.v2+json {"email":"ann@x.test","first_name":"Ann","id":1,"last_name":"Lee"}
Accept: v2 优先 (q 值) → 200 application/vnd.app.v2+json {"email":"ann@x.test","first_name":"Ann","id":1,"last_name":"Lee"}
Accept: */* → 200 application/vnd.app.v1+json {"id":1,"name":"Ann Lee"}
Accept: text/html → 406 text/html
X-API-Version: 2 → 200 application/vnd.app.v2+json {"email":"ann@x.test","first_name":"Ann","id":1,"last_name":"Lee"}
X-API-Version: 9 → 400 text/html
响应里的 Vary 头: None (Flask 不会自动加;共享缓存会把 v1 与 v2 混在一起)URL 版本:2 个版本 × 1 条规则 = 2 条规则;请求头版本:1 条规则