API Versioning in REST
Published on
As APIs evolve, maintaining backward compatibility becomes crucial. This article explores common strategies for versioning RESTful APIs and provides best‑practice recommendations.
Why Version Your API?
- Introduce new features without breaking existing clients.
- Deprecate outdated endpoints safely.
- Maintain a clear contract between server and consumer.
Versioning Strategies
URI Versioning
GET /v1/users
GET /v2/users?include=address
Embedding the version number directly in the URL is explicit and easy to route.
Header Versioning
GET /users
Accept: application/vnd.myapi.v2+json
Clients specify the desired version in a custom media type. This keeps URLs clean but requires more sophisticated content negotiation.
Query Parameter Versioning
GET /users?api-version=2
Simple to implement, but can be overlooked by caching layers.
Best Practices
- Never break existing contracts. Treat older versions as read‑only.
- Provide clear deprecation timelines. Communicate changes well in advance.
- Document each version. Keep separate OpenAPI specs per version.
- Maintain a default version. Serve the latest stable version when none is specified.
Sample Implementation (Node.js/Express)
const express = require('express');
const app = express();
app.get('/v1/users', (req, res) => {
res.json([{id:1,name:'Alice'}]); // legacy fields
});
app.get('/v2/users', (req, res) => {
res.json([{id:1,fullName:'Alice Smith',address:{city:'NY'}}]); // new schema
});
app.listen(3000,()=>console.log('API running on :3000'));