Details
Content Negotiation in HTTP is employed to determine the best format for a resource representation, based on the client’s capabilities and preferences using HTTP headers.
Key headers for this mechanism include Accept, Accept-Charset, Accept-Encoding, and Accept-Language.
The Accept header is particularly significant as it allows clients to specify media types and their quality values (q values), which indicate preferences with a range from 0 to 1. The higher the q value, the more preferable the media type.
Common Use Cases
- Media Delivery: Dynamically serving media in formats suitable for different devices.
- Internationalization: Delivering content localized in the user’s preferred language.
- API Versioning: Handling different versions of APIs by serving JSON, XML, or other formats.
- Optimized Web Browsing: Tailoring web assets to device or connection quality.
Mermaid Sequence Diagram
sequenceDiagram
participant C as Client
participant S as Server
C->>S: HTTP GET /tasks
Note over C,S: Client sends Accept headers with preferences
S->>C: Evaluate Accept headers
alt Successful Negotiation
S->>C: HTTP 200 OK with Content-Type
Note over C,S: Tasks served in preferred format
else No Acceptable Representation
S->>C: HTTP 406 Not Acceptable
end
Examples
Example 1: Simple Accept Header for JSON
Client Request:
GET /tasks HTTP/1.1
Host: example.com
Accept: application/json
Server Response (JSON supported):
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: ...
{
"tasks": [
{"id": 1, "description": "Update project plan"},
{"id": 2, "description": "Call client"}
]
}
Example 2: Simple Accept Header for XML
Client Request:
GET /tasks HTTP/1.1
Host: example.com
Accept: application/xml
Server Response (if XML is available):
HTTP/1.1 200 OK
Content-Type: application/xml
Content-Length: ...
<tasks>
<task id="1">
<description>Update project plan</description>
</task>
<task id="2">
<description>Call client</description>
</task>
</tasks>
Example 3: Using q Values with XML and JSON
Client Request:
GET /tasks HTTP/1.1
Host: example.com
Accept: application/json;q=0.5, application/xml;q=0.8
Server Response (Preferring XML as indicated by q values):
HTTP/1.1 200 OK
Content-Type: application/xml
Content-Length: ...
<tasks>
<task id="1">
<description>Update project plan</description>
</task>
<task id="2">
<description>Call client</description>
</task>
</tasks>
Example 4: Fetching Tasks as CSV with q Values
Client Request:
GET /tasks HTTP/1.1
Host: example.com
Accept: text/csv;q=1.0, application/json;q=0.8
Server Response (CSV format as the highest q value):
HTTP/1.1 200 OK
Content-Type: text/csv
Content-Length: ...
id,description
1,Update project plan
2,Call client