REST API Versioning Strategies
You need to change your API but can't break existing clients. Here are your options.
Why Version?
Your API has users. You need to make breaking changes. What do you do?
Options: 1. Break everyone (don't do this) 2. Never change anything (technical debt forever) 3. Version your API
Strategy 1: URL Path Versioning
GET /api/v1/users
GET /api/v2/users
Pros:
- Obvious and explicit
- Easy to see which version you're using
- Cache-friendly
Cons:
- URL pollution
- Have to maintain multiple routes
// Express implementation
app.use('/api/v1', v1Router);
app.use('/api/v2', v2Router);
This is the most common approach. I default to it.
Strategy 2: Query Parameter
GET /api/users?version=1
GET /api/users?version=2
Pros:
- Single URL structure
- Optional parameter
Cons:
- Easy to forget
- Caching complications
Strategy 3: Header Versioning
GET /api/users
Accept: application/vnd.myapi.v2+json
Or custom header:
GET /api/users
X-API-Version: 2
Pros:
- Clean URLs
- RESTfully pure
Cons:
- Hidden from URL inspection
- Harder to test in browser
My Preference
**URL path versioning** (`/api/v2/`) for most cases.
Why:
- Explicit > implicit
- Easy to document
- Easy to test
- Easy to route
Versioning Philosophy
Don't Version for Every Change
Non-breaking changes don't need a new version:
- Adding new fields to responses
- Adding new optional parameters
- Adding new endpoints
Do Version for Breaking Changes
- Removing fields
- Renaming fields
- Changing field types
- Changing endpoint behavior
Deprecation Period
// Response header
app.use('/api/v1', (req, res, next) => {
res.set('X-API-Deprecated', 'true');
res.set('X-API-Sunset', '2025-12-31');
next();
}, v1Router);
Give clients time to migrate.
The Practical Approach
1. **Start with v1** - No versioning until you need it 2. **Add v2 when breaking** - Support both for a while 3. **Document the diff** - What changed between versions 4. **Set a sunset date** - When v1 goes away 5. **Communicate early** - Email API users about deprecation
Your future self (and your users) will thank you.