Header-Based Versioning
You'll learn how to version REST APIs using HTTP headers instead of the URL path, trading cleaner URIs for added request complexity.
The Core Idea
Header-based versioning keeps your API version information out of the resource path and places it in HTTP headers instead. Rather than /v1/users, your endpoint stays simply /users, and clients specify the version they want through a custom header like API-Version: 1 or through content negotiation using the standard Accept header with custom media types.
Two Common Approaches
Custom Header Versioning
Clients send a custom header with each request:
GET /users
API-Version: 2
The URI remains clean and version-agnostic. Your server reads the header to determine which version of the logic to invoke.
Accept Header Versioning
Clients use the standard Accept header with vendor-specific media types:
GET /users
Accept: application/vnd.myapp.v2+json
This leverages HTTP's built-in content negotiation mechanism and follows REST principles more closely.
The Trade-off
Pros: URIs stay clean and don't expose versioning concerns. The same resource identifier (/users/123) refers to the same conceptual resource across versions, which feels more RESTful.
Cons: Headers are less visible than URIs—harder to test in browsers, harder to debug, and easier to forget. Clients must explicitly set headers, adding complexity. Caching and intermediate proxies may ignore custom headers, causing unexpected behavior.
Analogy
Think of it like ordering at a restaurant: URI versioning is like saying "I want the 2023 menu," while header-based versioning is like ordering from "the menu" but whispering your preferred recipe year to the waiter. The dish name stays the same; the preparation varies.
Key Takeaway: Header-based versioning keeps URIs clean and resource-focused but requires clients to explicitly manage version information in request headers, adding invisible complexity.