Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท Getting Started

Parsers, Renderers and Content Negotiation

Learn how DRF picks parsers for request bodies and renderers for responses, how the Accept header and ?format= work, and how to enable the browsable API.

One endpoint can speak several formats. The same Response({"title": "Dune"}) can be sent as JSON to a mobile app, as a styled HTML page to a developer in a browser, or as XML to a legacy system. DRF makes this possible with two pluggable families of classes: parsers read the request body, and renderers write the response body. Content negotiation is the process that chooses among them for each request.

You rarely write these classes yourself, but you must know how they are selected, because that explains errors such as 415 Unsupported Media Type and why your browser shows a pretty page while curl shows raw JSON.

Parsers: reading the request

A parser turns a body into data for request.data. DRF ships these:

Parser Media type Result
JSONParser application/json dicts, lists, numbers, booleans
FormParser application/x-www-form-urlencoded a QueryDict of strings
MultiPartParser multipart/form-data a QueryDict, including uploaded files
FileUploadParser any the raw file body

DRF reads the request's Content-Type header and picks the first parser whose media type matches. If nothing matches, it answers 415. The defaults are JSON, form and multipart, set in the DEFAULT_PARSER_CLASSES setting. You can change them globally or per view.

Python Restricting parsers on one view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Observe that @parser_classes must come below @api_view (it is applied first). A mismatched body gets 415, a body with the right type but invalid syntax gets 400 with a ParseError message. Both are produced for you.

Renderers: writing the response

A renderer turns the data of a Response into bytes. The most important ones:

Renderer Media type Typical use
JSONRenderer application/json The default for programs
BrowsableAPIRenderer text/html The interactive API page in a browser
AdminRenderer text/html A simple admin-style HTML interface
TemplateHTMLRenderer text/html Render a Django template from the data
StaticHTMLRenderer text/html Return a ready-made HTML string
HTMLFormRenderer text/html Render serializer forms inside the browsable API

The default renderer list is JSON first, then the browsable API. A request that asks for JSON gets JSON; a browser asking for HTML gets the browsable page. You can control this with the DEFAULT_RENDERER_CLASSES setting, or per view with @renderer_classes.

Content negotiation in action

DRF's default negotiator compares the client's Accept header with the available renderers and picks the best match. It also supports two overrides:

  • A format suffix or query parameter. By default the URL ?format=json forces the JSON renderer. This is handy in a browser address bar.
  • The first renderer wins when the client sends Accept: */*, which is why JSON should be first in the list.
Python The Accept header and ?format=

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The browsable API only works because the setup block lists rest_framework in INSTALLED_APPS and enables Django's template engine with APP_DIRS; DRF ships its HTML templates inside the package. Asking for a format nobody provides, here XML, yields 406 Not Acceptable. In a real project the browsable API is a great learning and debugging tool: it renders forms for POST and PUT, shows the allowed methods and links to the pages that you reach through hyperlinks.

Setting defaults in settings.py

Everything above can be changed once for the whole project in the REST_FRAMEWORK dictionary. A common production setup serves JSON only, which disables the browsable API for security and speed:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": [
        "rest_framework.renderers.JSONRenderer",
    ],
    "DEFAULT_PARSER_CLASSES": [
        "rest_framework.parsers.JSONParser",
    ],
}

During development you might keep the browsable renderer too and remove it only in the production settings file. A third-party package such as djangorestframework-xml or djangorestframework-yaml adds extra formats; you install it and add its renderer and parser to the lists.

Writing a tiny custom renderer

A renderer needs a media_type, a format and a render() method that returns bytes. The example below renders a CSV for a list of flat dictionaries. It is short enough to show the whole idea.

Python A custom CSV renderer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Because the view lists JSON first, a request without preferences gets JSON. ?format=csv and Accept: text/csv both select the new renderer. Your view code did not change at all: it only returned data. That separation, data in the view and format in the renderer, is the whole point of the design.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which header does DRF read to choose a parser?

    Content-Type describes the request body, so it selects the parser. Accept selects the renderer.
  2. 2. What status does DRF return when no parser matches the request body's media type?

    415 Unsupported Media Type is the correct answer when the body format cannot be parsed.
  3. 3. Why should JSONRenderer be listed first in the renderer list?

    With a wildcard Accept header the first renderer wins, so the list order is the default format.
  4. 4. How can you force the JSON renderer from a browser address bar?

    The default URL query override is ?format=. It selects the renderer whose format attribute matches.

Summary

  • Parsers read the body according to Content-Type; renderers write the response according to Accept or ?format=.
  • Defaults: JSON, form and multipart parsers; JSON and browsable API renderers.
  • No matching parser gives 415, malformed content gives 400, and no acceptable renderer gives 406.
  • Limit formats per view with @parser_classes and @renderer_classes, or globally in REST_FRAMEWORK.
  • A custom renderer needs only media_type, format and render().

Next: Serializer Basics