Chapter 8: API Versioning
Chapter 8 of 14
Chapter 8: API Versioning
8.1 Versioning Strategies
API versioning allows you to make changes without breaking existing clients.
URL Versioning:
// Most common approach
/api/v1/users
/api/v2/users
app.use('/api/v1', v1Routes);
app.use('/api/v2', v2Routes);
Header Versioning:
// Version in Accept header
Accept: application/vnd.api+json;version=1
app.use((req, res, next) => {
const version = req.headers.accept?.match(/version=(d+)/)?.[1] || '1';
req.apiVersion = version;
next();
});
Query Parameter Versioning:
// Less common
/api/users?version=1
// Implementation
app.use((req, res, next) => {
req.apiVersion = req.query.version || '1';
next();
});
8.2 Versioning Best Practices
- Start with v1 from the beginning
- Maintain backward compatibility when possible
- Deprecate old versions with clear timelines
- Document breaking changes
- Provide migration guides