0
0
Rest APIprogramming~5 mins

Content negotiation in Rest API

Choose your learning style9 modes available
Introduction

Content negotiation helps a server decide what format to send data in, based on what the client prefers. This makes communication smooth and flexible.

When a website needs to send data as JSON or XML depending on the user's device.
When an API supports multiple languages or formats and must choose the right one.
When a mobile app requests data and wants it in a smaller, efficient format.
When a browser asks for a webpage and the server can send HTML or plain text.
When different clients expect different data types from the same API endpoint.
Syntax
Rest API
GET /resource HTTP/1.1
Host: example.com
Accept: application/json

The Accept header tells the server what format the client wants.

The server reads this header and sends the response in the requested format if possible.

Examples
The client asks for JSON data.
Rest API
Accept: application/json
The client asks for HTML content.
Rest API
Accept: text/html
The client prefers XML but will accept JSON if XML is not available.
Rest API
Accept: application/xml, application/json;q=0.9
Sample Program

This small web server sends data in JSON if the client asks for JSON, in XML if XML is requested, or plain text otherwise.

Rest API
from flask import Flask, request, jsonify, Response

app = Flask(__name__)

@app.route('/data')
def data():
    sample = {'message': 'Hello, world!'}
    accept = request.headers.get('Accept', '')
    if 'application/json' in accept:
        return jsonify(sample)
    elif 'application/xml' in accept:
        xml_response = f"<message>{sample['message']}</message>"
        return Response(xml_response, mimetype='application/xml')
    else:
        return 'Hello, world!', 200, {'Content-Type': 'text/plain'}

if __name__ == '__main__':
    app.run(debug=True)
OutputSuccess
Important Notes

Always check the Accept header to decide response format.

If the client does not specify, send a default format like JSON or plain text.

Use quality values (q=) to prioritize formats if multiple are accepted.

Summary

Content negotiation lets servers send data in the format clients want.

Clients use the Accept header to tell their preferences.

Servers check this header and respond with the best matching format.