How to Version REST API: Best Practices and Examples
To version a REST API, use
URL path (e.g., /v1/resource), query parameters (e.g., ?version=1), or custom headers (e.g., X-API-Version: 1). This helps clients know which API version they are using and allows safe updates without breaking existing users.Syntax
There are three common ways to specify API versions:
- URL Path: Add version number in the URL path, e.g.,
/v1/users. - Query Parameter: Add version as a query string, e.g.,
/users?version=1. - Custom Header: Send version info in HTTP headers, e.g.,
X-API-Version: 1.
http
GET /v1/users HTTP/1.1 Host: api.example.com GET /users?version=1 HTTP/1.1 Host: api.example.com GET /users HTTP/1.1 Host: api.example.com X-API-Version: 1
Example
This example shows a simple Node.js Express server handling API versioning via URL path.
javascript
import express from 'express'; const app = express(); // Version 1 endpoint app.get('/v1/greet', (req, res) => { res.send('Hello from API version 1'); }); // Version 2 endpoint app.get('/v2/greet', (req, res) => { res.send('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 REST APIs include:
- Not including version info, causing breaking changes for clients.
- Mixing multiple versioning methods, which confuses clients.
- Using headers only without fallback, making testing harder.
- Changing API behavior without updating version, breaking backward compatibility.
http
/* Wrong: No version in URL or headers */ GET /users HTTP/1.1 Host: api.example.com /* Right: Version in URL path */ GET /v1/users HTTP/1.1 Host: api.example.com
Quick Reference
| Versioning Method | Example | Pros | Cons |
|---|---|---|---|
| URL Path | /v1/resource | Easy to cache and test | URL changes with each version |
| Query Parameter | /resource?version=1 | Simple to add, flexible | Can be ignored by caches |
| Custom Header | X-API-Version: 1 | Keeps URL clean | Harder to test and cache |
Key Takeaways
Always include a clear version identifier in your REST API to avoid breaking clients.
Use URL path versioning for simplicity and better caching support.
Avoid mixing multiple versioning methods to keep your API consistent.
Communicate version changes clearly to your API users.
Test all versions independently to ensure backward compatibility.