Implementing API Versioning
1. Implementing URL Path Versioning
| Aspect | Detail |
|---|---|
| Format | /v{n}/resource |
| Pros | Visible, cacheable, easy to route |
| Cons | Resource has multiple URIs |
Example: Versioned controller
@RestController
@RequestMapping("/v1/orders")
public class OrderControllerV1 { ... }
2. Implementing Header-Based Versioning
| Header | Example |
|---|---|
| Custom | API-Version: 2 |
| Spring | @RequestMapping(headers = "API-Version=2") |
| Pro | Clean URLs |
| Con | Less discoverable, harder to test in browser |
3. Implementing Query Parameter Versioning
| Aspect | Detail |
|---|---|
| Format | ?version=2 |
| Pro | Easy fallback to default |
| Con | Caches must include in key |
4. Implementing Content Negotiation Versioning
| Header | Example |
|---|---|
| Accept | application/vnd.acme.v2+json |
| Spring | @RequestMapping(produces = "application/vnd.acme.v2+json") |
| Pro | RESTful, leverages existing header |
| Con | Verbose, harder for casual clients |
5. Implementing Versioned Controllers
| Strategy | Detail |
|---|---|
| One per version | Independent evolution |
| Shared service | Logic centralized; controllers map |
| Adapter pattern | v1 controller → v2 service via adapter |
6. Implementing Versioned DTOs
Example: Version packages
com.acme.api.v1.OrderResponse
com.acme.api.v2.OrderResponse (added 'channel' field)
com.acme.api.mapper.OrderMapperV1, OrderMapperV2
7. Implementing Backward Compatibility Logic
| Change | Compatible? |
|---|---|
| Add optional field (response) | Yes |
| Add required field (request) | No |
| Remove field | No |
| Rename field | No (use alias) |
| Change type | No |
| Loosen validation | Yes |
| Tighten validation | No |
8. Implementing Deprecation Warnings
Example: Deprecation headers
HTTP/1.1 200 OK
Deprecation: true
Sunset: Sat, 31 Dec 2026 23:59:59 GMT
Link: </v2/orders>; rel="successor-version"
9. Implementing Version Migration Logic
| Approach | Detail |
|---|---|
| Translation layer | v1 request → v2 internal |
| Default values | Fill new required fields |
| Field rewrite | Old name → new name |
10. Managing Parallel Version Support
| Concern | Practice |
|---|---|
| N + 1 versions | Maintain current + previous |
| Shared core logic | Avoid duplicate bugs |
| Test matrix | Contract tests per version |
11. Implementing Version Negotiation
| Step | Detail |
|---|---|
| Read version header | API-Version or Accept |
| Default on absent | Latest stable or earliest supported |
| Reject unsupported | 406 Not Acceptable |