[ADP-353] Content Negotiation
Overview
Content negotiation is a mechanism that allows a server to select the best representation of a resource based on the client's preferences. It enables different versions of a response (like HTML, XML, JSON, etc.) for the same resource, enhancing API accessibility.
There are two main types of content negotiation:
- Proactive (Server-driven): The server selects the representation based on the client's stated preferences.
- Reactive (Client-driven or Agent-driven): The client specifies the representation in the request.
Server-driven negotiation is the most commonly used method, where the Accept header is used by HTTP clients to tell the server what content types they'll accept.
TIP
💡 SHOULD NOT tackle client-driven negotiation unless you document the progress of negotiation well.
Guidance
- SHOULD return
application/json
compatible MIME type according to RFC - SHOULD design a specific API for i18n preference instead of relying on the Accept-Language header
- MUST NOT use User-Agent for content negotiation
Relative HTTP headers
Request
- Accept
- Accept-Encoding
- Accept-CH
For detailed information on these headers, refer to ADP-121.
Response
- Content-Type, See ADP-126
- Content-Encoding
- Language
- Vary
For detailed information on these headers, refer to ADP-121.
Example
Design an API to fetch assets by url or image type on demand
http
GET /assets/asset-id HTTP/1.1
Accept: image/jpeg
HTTP/1.1 200 OK
Content-Type: image/jpeg
(binary)
http
GET /assets/asset-id HTTP/1.1
Accept: application/json
HTTP/1.1 200 OK
Content-Type: application/json
{
"url": "....",
}
Design an API to adopt different modifier to the same resource
http
GET /api-principles/1
Accept: application/vnd.my-corp.alive-app.api-principle.simplified+json
200
Content-Type: application/vnd.my-corp.alive-app.api-principle.simplified+json
{
"title": "SHOULD adopt best practices",
"principleId": 1
}
http
GET /api-principles/1
Accept: application/vnd.my-corp.alive-app.api-principle+json
200
Content-Type: application/vnd.my-corp.alive-app.api-principle+json
{
"title": "SHOULD adopt best practices",
"principleId": 1,
"examples": [],
"references": [],
"designThing": "...."
}