Skip to content

Content Negotiation

Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client preferences. DRF uses content negotiation to determine the most appropriate renderer and parser to use for a request.

How it works

When a request is received, DRF's content negotiation class examines the request (particularly the Accept header) and the available renderers. It selects the best match to format the response.

Similarly, it uses the Content-Type header to determine the appropriate parser for the incoming request data.

Setting Content Negotiation

You can set the default content negotiation class globally in your settings.py:

python
REST_FRAMEWORK = {
    'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'rest_framework.negotiation.DefaultContentNegotiation'
}

Or you can set it on a per-view basis:

Class-Based Views

python
from rest_framework.negotiation import DefaultContentNegotiation
from rest_framework.views import APIView

class ExampleView(APIView):
    content_negotiation_class = DefaultContentNegotiation

Function-Based Views

DRF does not provide a direct decorator for setting the content negotiation class on function-based views. It relies on the global setting or standard request parsing.

Custom Content Negotiation

If you need custom logic for selecting renderers and parsers, you can create a custom content negotiation class by subclassing BaseContentNegotiation and overriding the select_parser() and select_renderer() methods.

python
from rest_framework.negotiation import BaseContentNegotiation

class IgnoreClientContentNegotiation(BaseContentNegotiation):
    def select_parser(self, request, parsers):
        return parsers[0]

    def select_renderer(self, request, renderers, format_suffix):
        return (renderers[0], renderers[0].media_type)