How content negotiation works in REST
· Category: API & REST
Short answer
Content negotiation allows clients and servers to agree on the best representation format for a resource based on client capabilities and server offerings.
Steps
- The client sends an Accept header listing preferred media types with quality values.
- The server evaluates its available representations against the client's preferences.
- The server selects the most appropriate format and indicates it in Content-Type.
- If no acceptable format is available, the server returns 406 Not Acceptable.
- Similarly, the client can send Accept-Encoding and Accept-Language for compression and language preferences.
Tips
- Support JSON as a baseline since it is universally understood.
- Use content negotiation for versioning only when URL versioning is impractical.
- Provide clear error messages when negotiation fails.
- Test with clients that send wildcard Accept headers.
Common issues
- Servers ignoring the Accept header and always returning JSON.
- Ambiguous quality values causing unexpected format selection.
- Clients not handling 406 responses gracefully.
- Complex negotiation logic slowing down request processing.
Example
curl -X GET https://api.example.com/users -H "Accept: application/json" -H "Authorization: Bearer $TOKEN"
This curl command demonstrates a standard GET request with headers for content negotiation and bearer token authentication.