0
0
Rest-apiConceptBeginner · 3 min read

What is Accept Header in REST: Explanation and Example

The Accept header in REST APIs tells the server what type of response format the client wants, like JSON or XML. It helps the server send data in a format the client can understand.
⚙️

How It Works

Imagine you order a drink at a café and specify if you want it in a glass or a cup. The Accept header works similarly in REST APIs. When a client (like a web browser or app) sends a request to a server, it uses the Accept header to say, "I prefer the response in this format." Common formats include application/json for JSON data or application/xml for XML data.

The server reads this header and tries to send the response in the requested format. If it can't, it may send a default format or an error. This way, the client and server agree on how data is shared, making communication smooth and clear.

💻

Example

This example shows a simple HTTP GET request with an Accept header asking for JSON data. The server responds with JSON format.

http
GET /api/users HTTP/1.1
Host: example.com
Accept: application/json
Output
{ "users": [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"} ] }
🎯

When to Use

Use the Accept header when your client needs data in a specific format. For example, a web app might want JSON because it's easy to work with in JavaScript, while another system might prefer XML for legacy reasons.

It is especially useful in APIs that support multiple response formats. By setting the Accept header, clients ensure they get data they can process without extra conversion.

Key Points

  • The Accept header tells the server the preferred response format.
  • Common formats include JSON (application/json) and XML (application/xml).
  • If the server can't provide the requested format, it may send a default or an error.
  • Using Accept helps clients and servers communicate clearly and avoid confusion.

Key Takeaways

The Accept header specifies the response format the client wants from the server.
It enables flexible communication by supporting multiple data formats like JSON and XML.
Always set the Accept header when your client requires a specific data format.
Servers use the Accept header to decide how to format the response.
If unsupported, the server may return a default format or an error.