api-versioning-strategy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Versioning Strategy

API版本控制策略

Produce a complete API versioning strategy document that gives a service team durable, consistent rules for evolving their API without breaking consumers. This document covers the versioning scheme selection (with rationale), lifecycle policy from introduction through sunset, a precise breaking-change classification, and all the communication artifacts a team needs when deprecating a version. Engineers should be able to hand this document to a new team member or external consumer and have them understand exactly what to expect.
产出一份完整的API版本控制策略文档,为服务团队提供持久、一致的规则,确保在演进API时不会破坏消费者体验。本文档涵盖版本控制方案选择及理由、从发布到下线的生命周期策略、精准的破坏性变更分类,以及团队在弃用版本时所需的所有沟通工件。工程师可将此文档交给新团队成员或外部消费者,让他们清晰了解预期规则。

Required Inputs

必要输入项

Ask for these if not already provided:
  • API type — REST, GraphQL, or gRPC (each has different versioning mechanics)
  • Current versioning approach — URL path (
    /v1/
    ), request header, query parameter, or none; if none, document starts fresh
  • Number of existing versions and active consumer count — needed to size the lifecycle policy and migration scope
  • Deprecation timeline constraints — any hard deadlines (contract SLAs, compliance windows, annual release cycles)
  • Consumer type — internal teams only, external partners, public API, or mix (affects communication channel choices)
If any input is missing, ask before producing the document. For GraphQL, note that the versioning approach differs substantially (schema evolution over versioning) and tailor the scheme section accordingly.
若未提供以下信息,请主动询问:
  • API类型 — REST、GraphQL或gRPC(每种类型的版本控制机制不同)
  • 当前版本控制方式 — URL路径(
    /v1/
    )、请求头、查询参数,或无版本控制;若无,则文档从零开始制定
  • 现有版本数量及活跃消费者数量 — 用于确定生命周期策略规模和迁移范围
  • 弃用时间线约束 — 任何硬性截止日期(合同SLA、合规窗口期、年度发布周期)
  • 消费者类型 — 仅内部团队、外部合作伙伴、公开API,或混合类型(影响沟通渠道选择)
若缺少任何输入项,请先询问再生成文档。对于GraphQL,需注意其版本控制方式差异较大(优先采用Schema演进而非版本划分),并相应调整方案部分内容。

Output Format

输出格式



API Versioning Strategy: [Service Name]

API版本控制策略:[服务名称]

Owner: [Team Name] API Type: [REST / GraphQL / gRPC] Document Version: 1.0 Last Reviewed: [Date] Next Review: [Date + 6 months]

所有者: [团队名称] API类型: [REST / GraphQL / gRPC] 文档版本: 1.0 最后审核日期: [日期] 下次审核日期: [日期 + 6个月]

1. Versioning Scheme

1. 版本控制方案

Selected Approach: [URL Path / Request Header / Query Parameter]

选定方案:[URL路径 / 请求头 / 查询参数]

SchemeExampleProsConsVerdict
URL Path
/v2/orders
Visible in logs and bookmarks; trivial to routeViolates strict REST resource identity; clutters URL spaceRecommended for public-facing REST APIs
Accept
Header
Accept: application/vnd.[service].v2+json
Keeps URLs clean; proper content negotiationHarder to test in browser; less visible in logsRecommended for internal APIs with controlled clients
Query Parameter
/orders?version=2
Easy to retrofit without URL restructuringOften missed in client code; cache-key complicationsAcceptable only for read-heavy APIs already in production
GraphQL Schema EvolutionField deprecation +
@deprecated
directive
No versioning needed for additive changesRequires disciplined schema designRecommended for GraphQL APIs
Rationale for [chosen scheme]: [One paragraph explaining why this scheme fits the API type, consumer type, and operational context provided. Reference the specific inputs — e.g., "Because this API has external partners who integrate via generated clients, URL path versioning provides the most predictable routing behavior and eliminates header negotiation complexity."]
方案示例优点缺点结论
URL路径
/v2/orders
在日志和书签中可见;路由实现简单违反严格的REST资源标识规范;占用URL空间推荐用于面向公众的REST API
Accept
请求头
Accept: application/vnd.[service].v2+json
保持URL简洁;符合标准内容协商机制浏览器中测试难度大;日志中可见性低推荐用于客户端可控的内部API
查询参数
/orders?version=2
无需重构URL即可轻松改造客户端代码常遗漏;缓存键处理复杂仅适用于已上线的读密集型API
GraphQL Schema演进字段弃用 +
@deprecated
指令
新增变更无需版本划分需要严谨的Schema设计规范推荐用于GraphQL API
[选定方案]的选择理由: [一段文字解释该方案为何符合API类型、消费者类型及提供的运营环境。参考具体输入项——例如:“由于本API的外部合作伙伴通过生成的客户端进行集成,URL路径版本控制提供了最可预测的路由行为,消除了请求头协商的复杂性。”]

Version Format

版本格式

[Base URL]/v{MAJOR}/{resource}

Examples:
  https://api.[company].com/v1/orders
  https://api.[company].com/v2/orders/{id}/items

Version identifier: integer only (v1, v2, v3)
No minor versions in the URL — minor/patch changes are non-breaking and deployed continuously.

[Base URL]/v{MAJOR}/{resource}

Examples:
  https://api.[company].com/v1/orders
  https://api.[company].com/v2/orders/{id}/items

Version identifier: integer only (v1, v2, v3)
No minor versions in the URL — minor/patch changes are non-breaking and deployed continuously.

2. Version Lifecycle Policy

2. 版本生命周期策略

Lifecycle Stages

生命周期阶段

  STABLE ──────────────────────────────────────────────────►
      ├─ STABLE        Active development, full SLA, new consumers allowed
      ├─ DEPRECATED    Announced, timeline posted, migration docs live.
      │                New consumers blocked. Existing consumers receive warnings.
      ├─ SUNSET        Requests return HTTP 410 Gone + migration pointer.
      │                30-day window before routing is removed.
      └─ RETIRED       Routing removed, docs archived, no traffic accepted.
StageDurationSLA AppliesNew Consumers AllowedRequired Action
StableUntil supersededYes — fullYesNone
Deprecated[12 months / adjust per constraint]Yes — degraded acceptableNoMigrate before sunset date
Sunset30-day windowBest-effort onlyNoMigrate immediately
RetiredPermanentNoneNo
Minimum Stable Period: A version must remain Stable for at least [6 / 12] months before deprecation can be announced.
Maximum Simultaneous Versions: No more than [2] versions in Stable or Deprecated status at any time. Releasing v3 requires committing to a sunset date for v1 in the same announcement.

  STABLE ──────────────────────────────────────────────────►
      ├─ STABLE        活跃开发中,提供完整SLA,允许新消费者接入
      ├─ DEPRECATED    已宣布弃用,发布时间线,迁移文档已上线。
      │                禁止新消费者接入。现有消费者会收到警告。
      ├─ SUNSET        请求返回HTTP 410 Gone + 迁移指引。
      │                移除路由前有30天窗口期。
      └─ RETIRED       路由已移除,文档已归档,不再接受任何流量。
阶段时长是否适用SLA是否允许新消费者必要操作
Stable直至被替代是——完整SLA
Deprecated[12个月 / 根据约束调整]是——允许降级服务在日落日期前完成迁移
Sunset30天窗口期仅提供尽力而为服务立即迁移
Retired永久
最小稳定周期: 版本必须保持Stable状态至少[6 / 12]个月,才可宣布弃用。
最大同时支持版本数: 任何时候处于Stable或Deprecated状态的版本不得超过[2]个。发布v3时,需在同一公告中承诺v1的日落日期。

3. Breaking vs. Non-Breaking Change Classification

3. 破坏性变更与非破坏性变更分类

Apply this table before every API change. If a change is marked Breaking, it requires a new major version. When uncertain, default to Breaking.
Change TypeSpecific ExampleClassificationRationale
Remove a response fieldDelete
order.legacy_id
from response
BreakingClients reading this field will null-pointer or fail
Rename a field
user_name
username
BreakingClients referencing old name receive null
Change field type
"amount": "10.00"
"amount": 10.00
BreakingType mismatch at deserialization
Make optional field required
email
required in POST body
BreakingExisting callers omitting it receive 400
Remove an endpoint
DELETE /v1/widgets/{id}
removed
BreakingExisting callers receive 404
Change HTTP method
GET /search
POST /search
BreakingBookmarked or cached GET calls fail
Change authentication schemeAPI key → OAuth2BreakingAll clients must re-authenticate
Restructure error response shapeError JSON schema changedBreakingError-handling code misparses responses
Expand enum values (response)New
status: "on_hold"
value returned
BreakingSwitch statements with no default fall through
Change pagination defaults
page_size
default 20 → 50
BreakingResponse length changes unexpectedly
Tighten input validationMax length 100 → 50BreakingPreviously valid inputs now rejected
Add new optional field to responseAdd
order.tax_breakdown
Non-BreakingClients ignore unknown fields per spec
Add new optional request parameterAdd
?include_archived=true
Non-BreakingIgnored by existing clients
Add a new endpoint
GET /v1/orders/{id}/audit
Non-BreakingNo existing client references it
Relax input validationMin length 10 → 5Non-BreakingExisting valid inputs remain valid
Performance or latency improvementResponse time reducedNon-Breaking
Add new enum value (request-only)Accept new
type: "express"
Non-BreakingExisting values still accepted

每次API变更前需对照此表。若变更被标记为破坏性变更,则需发布新的主版本。若不确定,默认按破坏性变更处理。
变更类型具体示例分类理由
删除响应字段从响应中删除
order.legacy_id
破坏性变更读取该字段的客户端会出现空指针或执行失败
字段重命名
user_name
username
破坏性变更引用旧字段名的客户端会收到空值
字段类型变更
"amount": "10.00"
"amount": 10.00
破坏性变更反序列化时会出现类型不匹配
可选字段改为必填POST请求体中
email
变为必填
破坏性变更未传入该字段的现有调用者会收到400错误
删除端点
DELETE /v1/widgets/{id}
被移除
破坏性变更现有调用者会收到404错误
HTTP方法变更
GET /search
POST /search
破坏性变更已收藏或缓存的GET请求会失败
认证方式变更API密钥 → OAuth2破坏性变更所有客户端必须重新认证
错误响应结构变更错误JSON Schema变更破坏性变更错误处理代码会解析失败
响应枚举值扩展返回新的
status: "on_hold"
破坏性变更无默认分支的switch语句会执行失败
分页默认值变更
page_size
默认值从20改为50
破坏性变更响应长度会意外变化
输入验证收紧最大长度从100改为50破坏性变更之前合法的输入现在会被拒绝
响应中新增可选字段添加
order.tax_breakdown
非破坏性变更客户端会根据规范忽略未知字段
请求中新增可选参数添加
?include_archived=true
非破坏性变更现有客户端会忽略该参数
新增端点
GET /v1/orders/{id}/audit
非破坏性变更无现有客户端引用该端点
输入验证放宽最小长度从10改为5非破坏性变更现有合法输入仍保持合法
性能或延迟优化响应时间缩短非破坏性变更
请求枚举值新增接受新的
type: "express"
非破坏性变更仍接受原有值

4. Deprecation Process

4. 弃用流程

Step-by-Step Deprecation Checklist

分步弃用检查清单

  • T-0 (Decision day): Engineering lead approves deprecation. New version confirmed Stable. Sunset date set.
  • T-0: Update API docs — add deprecation banner to all v[N] endpoint pages.
  • T-0: Add
    Deprecation
    and
    Sunset
    response headers to all v[N] responses (see format below).
  • T-0: Block new consumer onboarding for v[N] in API gateway and developer portal.
  • T-0: Send initial deprecation notice to all registered consumers (see Section 5 template).
  • T-0: Open tracking issue in engineering backlog linking all known consumers to their migration status.
  • T minus 30 days: Send 30-day warning to all consumers still sending v[N] traffic.
  • T minus 7 days: Send final warning. If consumer traffic > 100 req/day, escalate directly to their engineering lead.
  • Sunset date: Switch v[N] routing to return
    HTTP 410 Gone
    with body pointing to migration guide.
  • T plus 30 days: Remove routing rules. Archive documentation. Close tracking issue.
  • T-0(决策日): 工程负责人批准弃用。确认新版本已处于Stable状态。设定日落日期。
  • T-0: 更新API文档——在所有v[N]端点页面添加弃用横幅。
  • T-0: 为所有v[N]响应添加
    Deprecation
    Sunset
    响应头(格式见下文)。
  • T-0: 在API网关和开发者门户中阻止新消费者接入v[N]。
  • T-0: 向所有注册消费者发送初始弃用通知(见第5节模板)。
  • T-0: 在工程待办事项中创建跟踪问题,关联所有已知消费者及其迁移状态。
  • T减30天: 向仍在发送v[N]流量的所有消费者发送30天警告。
  • T减7天: 发送最终警告。若消费者流量>100请求/天,直接升级至其工程负责人。
  • 日落日期: 将v[N]路由切换为返回
    HTTP 410 Gone
    ,响应体指向迁移指南。
  • T加30天: 移除路由规则。归档文档。关闭跟踪问题。

Deprecation Response Headers

弃用响应头

http
HTTP/1.1 200 OK
Deprecation: true
Sunset: Sat, 01 Jan 2027 00:00:00 GMT
Link: <https://docs.[company].com/api/migration/v1-to-v2>; rel="successor-version"
http
HTTP/1.1 200 OK
Deprecation: true
Sunset: Sat, 01 Jan 2027 00:00:00 GMT
Link: <https://docs.[company].com/api/migration/v1-to-v2>; rel="successor-version"

Sunset Response Body

日落响应体

http
HTTP/1.1 410 Gone
Content-Type: application/json

{
  "error": "api_version_sunset",
  "message": "API v1 was sunset on 2027-01-01. Please migrate to v2.",
  "migration_guide": "https://docs.[company].com/api/migration/v1-to-v2",
  "support": "api-support@[company].com"
}

http
HTTP/1.1 410 Gone
Content-Type: application/json

{
  "error": "api_version_sunset",
  "message": "API v1 was sunset on 2027-01-01. Please migrate to v2.",
  "migration_guide": "https://docs.[company].com/api/migration/v1-to-v2",
  "support": "api-support@[company].com"
}

5. Client Communication Templates

5. 客户端沟通模板

Initial Deprecation Notice

初始弃用通知

Subject: [Action Required] [Service Name] API v[N] Deprecation — Sunset [Date]

Hi [Team / Partner Name],

We are deprecating [Service Name] API v[N], effective [Sunset Date].

What this means for you:
- v[N] continues to work normally until [Sunset Date]
- After [Sunset Date], all v[N] requests return HTTP 410 Gone
- v[N+1] is available today and fully stable

Your current usage: approximately [X] requests/day as of [Date].
Estimated migration effort: [Small: < 1 day | Medium: 1–3 days | Large: 3–10 days]

Migration resources:
  Migration guide:  [URL]
  Changelog:        [URL]
  Office hours:     [Date/Time/Link]
  Support:          [Slack channel or email]

Key dates:
  [Date]          Deprecation announced (today)
  [Date]          New consumer onboarding blocked for v[N]
  [Date]          30-day warning sent to remaining consumers
  [Sunset Date]   v[N] returns 410 Gone

Reply to this message or contact us at [channel] with questions.

[Your Name], [Team Name]
主题:[需采取行动] [服务名称] API v[N]弃用——日落日期[日期]

您好[团队/合作伙伴名称]:

我们将于[日落日期]起弃用[服务名称] API v[N]。

对您的影响:
- v[N]在[日落日期]前可正常使用
- [日落日期]后,所有v[N]请求将返回HTTP 410 Gone
- v[N+1]现已可用且完全稳定

您当前的使用情况:截至[日期],约[X]请求/天。
预计迁移工作量:[小:<1天 | 中:1-3天 | 大:3-10天]

迁移资源:
  迁移指南:[URL]
  更新日志:[URL]
  办公时间:[日期/时间/链接]
  支持渠道:[Slack频道或邮箱]

关键日期:
  [日期]  宣布弃用(今日)
  [日期]  阻止新消费者接入v[N]
  [日期]  向剩余消费者发送30天警告
  [日落日期] v[N]返回410 Gone

如有疑问,请回复此邮件或通过[渠道]联系我们。

[您的姓名],[团队名称]

30-Day Warning

30天警告

Subject: [30 Days Remaining] [Service Name] API v[N] sunsets [Date]

Hi [Team / Partner Name],

[Service Name] API v[N] sunsets in 30 days on [Date].

Your current v[N] traffic: [X] requests/day — migration is not yet complete.

If you have a technical blocker requiring an extension, contact us before
[Date minus 14 days]. Extensions require a documented blocker and a committed
migration completion date.

Migration guide: [URL] | Support: [channel]

主题:[剩余30天] [服务名称] API v[N]将于[日期]日落

您好[团队/合作伙伴名称]:

[服务名称] API v[N]将于30天后的[日期]日落。

您当前的v[N]流量:[X]请求/天——迁移尚未完成。

若您有技术障碍需要延期,请在[日期减14天]前联系我们。延期需提供书面障碍说明及承诺的迁移完成日期。

迁移指南:[URL] | 支持渠道:[渠道]

6. Migration Guide Template

6. 迁移指南模板

Publish one migration guide per version transition at
docs.[company].com/api/migration/v[N]-to-v[N+1]
.
markdown
undefined
为每个版本过渡发布一份迁移指南,地址为
docs.[company].com/api/migration/v[N]-to-v[N+1]
markdown
undefined

Migration Guide: v[N] → v[N+1]

迁移指南:v[N] → v[N+1]

Estimated effort: [Small: < 1 day | Medium: 1–3 days | Large: 3–10 days] Breaking changes in this guide: [count]
预计工作量: [小:<1天 | 中:1-3天 | 大:3-10天] 本指南中的破坏性变更数量: [数量]

Quick Start

快速开始

更新您的基础URL: 迁移前:https://api.[company].com/v[N]/ 迁移后:https://api.[company].com/v[N+1]/

Breaking Changes

破坏性变更

1. [Field Rename: user_name → username]

1. [字段重命名:user_name → username]

Affected endpoints:
GET /users/{id}
,
POST /users
Before (v[N]): { "user_name": "alice" }
After (v[N+1]): { "username": "alice" }
Migration: Replace all references to
user_name
with
username
in request builders and response parsers.
受影响端点:
GET /users/{id}
,
POST /users
迁移前(v[N]): { "user_name": "alice" }
迁移后(v[N+1]): { "username": "alice" }
迁移操作:在请求构建器和响应解析器中,将所有
user_name
引用替换为
username

2. [Next breaking change — repeat structure]

2. [下一个破坏性变更——重复上述结构]

New Capabilities in v[N+1]

v[N+1]中的新功能

FeatureDescriptionDocs
[Feature name][Brief description][Link]
功能描述文档链接
[功能名称][简要描述][链接]

SDK Upgrade Reference

SDK升级参考

LanguagePackagev[N+1] VersionInstall Command
Python
[company]-sdk
2.0.0
pip install [company]-sdk==2.0.0
Node.js
@[company]/sdk
2.0.0
npm install @[company]/sdk@2.0.0
Go
github.com/[company]/sdk-go
v2.0.0
go get github.com/[company]/sdk-go/v2
Java
com.[company]:sdk
2.0.0
Update pom.xml / build.gradle
语言包名称v[N+1]版本安装命令
Python
[company]-sdk
2.0.0
pip install [company]-sdk==2.0.0
Node.js
@[company]/sdk
2.0.0
npm install @[company]/sdk@2.0.0
Go
github.com/[company]/sdk-go
v2.0.0
go get github.com/[company]/sdk-go/v2
Java
com.[company]:sdk
2.0.0
更新pom.xml / build.gradle

Migration Validation Checklist

迁移验证检查清单

  • Base URL updated to v[N+1]
  • All renamed fields updated in request serializers
  • All renamed fields updated in response deserializers
  • Error-handling code updated for new error shape
  • Integration tests passing against v[N+1] in staging
  • Load test completed against v[N+1] — latency within acceptable range
  • Rollback plan documented if issues arise post-cutover

---
  • 基础URL已更新至v[N+1]
  • 请求序列化器中所有重命名字段已更新
  • 响应反序列化器中所有重命名字段已更新
  • 错误处理代码已适配新的错误结构
  • 集成测试在预发布环境中通过v[N+1]验证
  • 已针对v[N+1]完成负载测试——延迟在可接受范围内
  • 已记录切换后出现问题的回滚计划

---

7. Version-Specific Documentation

7. 特定版本文档

  • Maintain separate documentation pages for each Stable and Deprecated version.
  • Deprecated version docs carry a persistent banner: "This version is deprecated. Sunset date: [Date]. [Migrate to v[N+1]]."
  • OpenAPI specs, Protobuf definitions, or GraphQL schemas are tagged and archived per version in the repository under
    /api/v[N]/
    .
  • A root-level CHANGELOG.md records every breaking and non-breaking change by version — not buried in commit history.

  • 为每个Stable和Deprecated版本维护独立的文档页面。
  • Deprecated版本文档需显示永久横幅:“此版本已弃用。日落日期:[日期]。[迁移至v[N+1]]。”
  • OpenAPI规范、Protobuf定义或GraphQL Schema需按版本标记并归档在仓库的
    /api/v[N]/
    目录下。
  • 根目录下的CHANGELOG.md需按版本记录所有破坏性和非破坏性变更——不得隐藏在提交历史中。

8. SDK Versioning Alignment

8. SDK版本对齐

API VersionSDK Major VersionSDK GA DateSDK EOL Date
v[1]1.x[Date][API Sunset + 90 days]
v[2]2.x[Date]Active
  • SDK major versions align 1:1 with API major versions.
  • SDK minor versions track non-breaking API additions.
  • SDK EOL dates trail API sunset dates by 90 days to give consumers extra runway.
  • SDKs emit a runtime deprecation warning log line when the underlying API version is Deprecated.

Strategy authored by [Team Name] — questions to [Slack channel or email]

API版本SDK主版本SDK正式发布日期SDK终止支持日期
v[1]1.x[日期][API日落日期 + 90天]
v[2]2.x[日期]活跃支持中
  • SDK主版本与API主版本1:1对齐。
  • SDK次版本跟踪API的非破坏性新增功能。
  • SDK终止支持日期比API日落日期晚90天,为消费者提供额外过渡时间。
  • 当底层API版本被标记为Deprecated时,SDK会在运行时输出弃用警告日志。

本策略由[团队名称]制定——如有疑问请联系[Slack频道或邮箱]

Quality Checks

质量检查项

  • Versioning scheme recommendation includes explicit rationale tied to the API type and consumer type provided — not a generic recommendation
  • Breaking-change table covers at minimum: field removal, field rename, type change, making optional field required, endpoint removal, enum expansion, and default value change
  • Deprecation timeline durations are filled in with concrete values, not left as abstract placeholders
  • All three communication artifacts are present: initial deprecation notice, 30-day warning, and migration guide template
  • Sunset response headers (
    Deprecation
    ,
    Sunset
    ,
    Link
    ) use correct RFC date format and real URL structure
  • SDK versioning alignment table is present and ties SDK major versions explicitly to API major versions
  • Maximum simultaneous supported versions is stated with a concrete number
  • 版本控制方案建议包含与API类型和消费者类型绑定的明确理由——而非通用建议
  • 破坏性变更表至少涵盖:字段删除、字段重命名、类型变更、可选字段改必填、端点删除、枚举扩展、默认值变更
  • 弃用时间线已填充具体时长,而非抽象占位符
  • 包含所有三类沟通工件:初始弃用通知、30天警告、迁移指南模板
  • 日落响应头(
    Deprecation
    Sunset
    Link
    )使用正确的RFC日期格式和真实URL结构
  • 包含SDK版本对齐表,并明确将SDK主版本与API主版本绑定
  • 已明确最大同时支持版本数的具体数值