How would you support versioned response shapes for the same resource using content negotiation via custom media types instead of URL-based versioning?
Short answer
Media type versioning defines custom vendor-specific media types (like application/vnd.myapp.v2+json) that clients specify in their Accept header, with a custom formatter or action constraint selecting the correct response shape based on the requested version embedded in the…
Advertisement
AModel answer
Media type versioning defines custom vendor-specific media types (like application/vnd.myapp.v2+json) that clients specify in their Accept header, with a custom formatter or action constraint selecting the correct response shape based on the requested version embedded in the media type itself -- an alternative to URL-segment versioning that keeps URLs stable while still allowing multiple concurrent response contract versions.
[HttpGet("{id}")]
[Produces("application/vnd.myapp.v1+json", "application/vnd.myapp.v2+json")]
public IActionResult GetProduct(int id) {
var acceptHeader = Request.Headers.Accept.ToString();
return acceptHeader.Contains("v2")
? Ok(MapToV2(product))
: Ok(MapToV1(product));
}Real-world example
A REST purist API uses media-type versioning (application/vnd.api.v2+json) specifically to keep its resource URLs completely stable and semantically 'permanent' across contract versions, following stricter REST/HATEOAS principles than typical URL-segment versioning allows.
Likely follow-ups
- Why is media-type versioning less commonly adopted in practice than URL or header versioning?
- How would you document this versioning approach clearly in OpenAPI/Swagger?
Related topics