Content Negotiation and Accept Headers
You'll learn how clients and servers agree on response formats using HTTP headers to support multiple data representations.
The Core Idea
Imagine ordering food at a restaurant where the menu is available in English, Spanish, and French—you tell the waiter your preference, and they bring you the right version. Content negotiation works the same way: the client tells the server which response format it prefers (JSON, XML, HTML, etc.), and the server responds accordingly.
This happens through the Accept header in the HTTP request. The client specifies what media types it can handle, and the server selects the best match from what it supports.
How It Works
Client Request:
GET /api/users/123
Accept: application/json
The client is saying: "I prefer JSON."
Server Response:
HTTP/1.1 200 OK
Content-Type: application/json
{"id": 123, "name": "Alice"}
If the client requested Accept: application/xml instead, the same resource could be returned as:
<user>
<id>123</id>
<name>Alice</name>
</user>
Multiple Preferences
Clients can specify multiple formats with priorities (quality values):
Accept: application/json, application/xml;q=0.8, text/html;q=0.5
This means: "I prefer JSON, but I'll accept XML (80% preference) or HTML (50% preference)."
If the server cannot provide any requested format, it returns 406 Not Acceptable.
Why It Matters
Content negotiation lets a single API endpoint serve multiple client types—web browsers might want HTML, mobile apps want JSON, legacy systems need XML—all from the same URL. This keeps your API flexible without duplicating endpoints.
Key Takeaway:
Content negotiation via Accept headers lets clients request their preferred response format, enabling one API to serve multiple representations of the same resource.