API Versioning
The practice of managing changes to an API by creating multiple versions, allowing existing clients to continue using old versions while new clients adopt the latest.
Detailed Explanation
API versioning lets you evolve your API without breaking existing clients. When you make a breaking change (rename a field, change the response structure), you release a new version. Old clients continue using the old version; new clients use the new version.
Versioning strategies: URL path (`/v1/users`), header (`Accept: application/vnd.api.v1+json`), query parameter (`?version=1`), and content negotiation. URL path versioning is the most common and simplest to implement. GraphQL avoids versioning by evolving the schema (adding new fields, deprecating old ones).
Why It Matters
Versioning prevents breaking changes from breaking existing clients. It enables safe API evolution and backward compatibility.
Real-World Example
Stripe uses date-based versioning: `/v1/charges` with header `Stripe-Version: 2024-01-01`. Each version is stable; new features are added as new endpoints or optional fields.
When to Use
When you need to make breaking changes to a public API. Internal APIs may not need formal versioning if you can coordinate changes across teams.
Advantages
- Backward compatibility for existing clients
- Safe API evolution
- Gradual migration for clients
- Clear deprecation timeline
- Multiple versions can coexist
Disadvantages
- Maintaining multiple versions is costly
- Documentation complexity increases
- Code duplication across versions
- Deprecation management overhead
- Can lead to version sprawl
Frequently Asked Questions
When should I version my API?
Version when you make breaking changes: removing/renaming fields, changing authentication, or modifying response structure. Non-breaking additions (new fields, new endpoints) don't require versioning.
What is the best versioning strategy?
URL path versioning (`/v1/users`) is the simplest and most common. Header versioning is cleaner but harder to test. Choose based on your API's audience and complexity. For GraphQL, use schema evolution instead.
How long should I maintain old API versions?
Typically 12-24 months after the new version is released. Give clients time to migrate, provide clear deprecation notices, and communicate the timeline. Don't maintain old versions indefinitely.
Can GraphQL avoid versioning?
Yes. GraphQL encourages schema evolution: add new fields (non-breaking), deprecate old fields with @deprecated, and remove them later. Clients only request the fields they need, so additions don't break existing queries.
How do I deprecate an API version?
Add deprecation headers (Sunset, Deprecation), publish a migration guide, notify clients via email/blog, set a removal date, and monitor usage of old versions. Don't remove old versions abruptly.