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

  1. The client sends an Accept header listing preferred media types with quality values.
  2. The server evaluates its available representations against the client's preferences.
  3. The server selects the most appropriate format and indicates it in Content-Type.
  4. If no acceptable format is available, the server returns 406 Not Acceptable.
  5. 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.