How does header-based API versioning work, and what's a scenario where it's preferred over URL segment versioning?
Short answer
Header-based versioning reads the version from a custom request header (like X-Api-Version) rather than the URL path, configured via options.ApiVersionReader = new HeaderApiVersionReader("X-Api-Version") -- preferred when you want completely stable, version-agnostic URLs (useful…
Advertisement
AModel answer
Header-based versioning reads the version from a custom request header (like X-Api-Version) rather than the URL path, configured via options.ApiVersionReader = new HeaderApiVersionReader("X-Api-Version") -- preferred when you want completely stable, version-agnostic URLs (useful for caching proxies keyed purely on path, or when the URL is meant to represent a permanent resource identity independent of API evolution).
builder.Services.AddApiVersioning(options => {
options.ApiVersionReader = new HeaderApiVersionReader("X-Api-Version");
});
// Client request:
// GET /api/products/5
// X-Api-Version: 2.0Real-world example
An internal service-to-service API uses header-based versioning specifically to keep resource URLs (used as stable identifiers in logs and distributed traces) completely unaffected by API version changes over time.
Likely follow-ups
- How do you combine multiple version readers (URL AND header) simultaneously?
- What are the caching implications of header-based versus URL-based versioning?
Related topics