Course contentsShow
← Web Development
Lesson 1499 of 2,98227. REST API Design for FrontendFree lesson

Content Negotiation with Accept Headers

Use Accept headers to request specific response formats like JSON, XML, or HTML from flexible APIs.

Content Negotiation with Accept Headers

What you'll learn: How to use the Accept header to request specific response formats (JSON, XML, HTML) from APIs that support multiple representations.


The Core Idea

Content negotiation is like ordering at a restaurant that offers the same dish in different styles. The API is the kitchen, and the Accept header is how you tell the server which "style" of data you'd like to receive—JSON for JavaScript apps, XML for legacy systems, or HTML for browsers.

When your frontend makes a request, it includes an Accept header specifying preferred media types. The server examines this header and responds with the format that best matches your request (if supported).

How It Works

The Accept header lists one or more MIME types (media types) in order of preference:

Accept: application/json

For multiple preferences with priority:

Accept: application/json, application/xml;q=0.9, text/html;q=0.8

The q parameter (quality factor) ranges from 0 to 1, indicating preference weight. Higher values mean higher preference.

Why This Matters for Frontend

Instead of building separate endpoints like /api/users.json and /api/users.xml, a well-designed REST API uses one endpoint (/api/users) and returns different formats based on the Accept header. Your frontend simply sets the appropriate header when fetching data.

When the server cannot fulfill your Accept request, it responds with 406 Not Acceptable, signaling a negotiation failure.

Key Takeaway: The Accept header enables flexible APIs to serve multiple representation formats from a single endpoint, letting your frontend explicitly request the data format it needs (typically JSON for modern web apps).