How to Use Header Versioning in REST APIs
Header versioning uses a custom HTTP header like
Accept-Version or X-API-Version to specify the API version. The client sends the version in the request header, and the server uses it to route or respond with the correct API version.Syntax
Header versioning requires the client to include a custom header in the HTTP request specifying the API version. Common header names are Accept-Version or X-API-Version.
The server reads this header to determine which version of the API to serve.
http
GET /resource HTTP/1.1
Host: api.example.com
Accept-Version: v1Example
This example shows a simple Node.js Express server that reads the X-API-Version header to serve different responses based on the API version requested.
javascript
import express from 'express'; const app = express(); app.get('/data', (req, res) => { const version = req.header('X-API-Version'); if (version === 'v1') { res.json({ message: 'Response from API version 1' }); } else if (version === 'v2') { res.json({ message: 'Response from API version 2 with new data' }); } else { res.status(400).json({ error: 'API version header missing or unsupported' }); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
- Forgetting to document the header name and supported versions for clients.
- Not handling missing or unsupported version headers, causing errors or unexpected responses.
- Mixing header versioning with URL or query parameter versioning can confuse clients and servers.
- Clients may cache responses ignoring the version header, leading to stale data.
javascript
/* Wrong: No version header check */ app.get('/data', (req, res) => { res.json({ message: 'Only one version served' }); }); /* Right: Check version header and respond accordingly */ app.get('/data', (req, res) => { const version = req.header('X-API-Version'); if (!version) { return res.status(400).json({ error: 'Missing API version header' }); } // handle versions... });
Quick Reference
Use these tips to implement header versioning effectively:
- Choose a clear header name like
X-API-VersionorAccept-Version. - Always validate the version header on the server.
- Return clear error messages if the version is missing or unsupported.
- Keep versioning consistent across your API.
- Document the versioning scheme for API users.
Key Takeaways
Use a custom HTTP header to specify API version in requests.
The server reads the version header to serve the correct API version.
Always validate and handle missing or unsupported version headers.
Keep versioning consistent and well documented for clients.
Avoid mixing header versioning with other versioning methods.