How to Version Microservice APIs: Best Practices and Examples
To version microservice APIs, use
URI versioning (e.g., /v1/resource), header versioning (custom headers like X-API-Version), or query parameter versioning (e.g., ?version=1). This helps maintain backward compatibility and allows clients to choose the API version they need.Syntax
API versioning can be done in three common ways:
- URI Versioning: Add the version number in the URL path.
- Header Versioning: Specify the version in a custom HTTP header.
- Query Parameter Versioning: Pass the version as a query parameter.
Each method lets clients request a specific API version without breaking existing integrations.
http
GET /v1/users HTTP/1.1 Host: api.example.com GET /users HTTP/1.1 Host: api.example.com X-API-Version: 1 GET /users?version=1 HTTP/1.1 Host: api.example.com
Example
This example shows a simple Node.js Express server handling URI versioning for two API versions.
javascript
const express = require('express'); const app = express(); // Version 1 API app.get('/v1/greet', (req, res) => { res.json({ message: 'Hello from API version 1' }); }); // Version 2 API app.get('/v2/greet', (req, res) => { res.json({ message: 'Hello from API version 2 with new features' }); }); app.listen(3000, () => { console.log('API server running on http://localhost:3000'); });
Output
API server running on http://localhost:3000
Common Pitfalls
Common mistakes when versioning microservice APIs include:
- Not maintaining backward compatibility, causing clients to break.
- Changing API behavior without updating the version.
- Using multiple versioning methods inconsistently.
- Ignoring documentation updates for new versions.
Always communicate version changes clearly and keep old versions running until clients migrate.
javascript
/* Wrong: Changing response format without version update */ app.get('/users', (req, res) => { // Changed response structure but URL/version unchanged res.json({ usersList: [] }); }); /* Right: Create new version endpoint */ app.get('/v2/users', (req, res) => { res.json({ usersList: [] }); });
Quick Reference
| Versioning Method | Description | Pros | Cons |
|---|---|---|---|
| URI Versioning | Version in URL path (e.g., /v1/resource) | Easy to cache and debug | URL changes can break links |
| Header Versioning | Version in custom HTTP header | Clean URLs, flexible | Harder to test and cache |
| Query Parameter | Version as query string (e.g., ?version=1) | Simple to implement | Can be ignored by caches |
Key Takeaways
Use clear versioning methods like URI, headers, or query parameters to avoid breaking clients.
Maintain backward compatibility by keeping old API versions active during transitions.
Document API versions and changes clearly for client developers.
Avoid mixing multiple versioning strategies inconsistently.
Test all API versions thoroughly before deployment.