Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 39 ยท Versioning and Documentation

The Browsable API, OPTIONS Metadata and Self-Documenting Views

Use and customize the Django REST Framework browsable API: HTML rendering, OPTIONS metadata, view names and descriptions from docstrings, custom metadata and turning the HTML renderer off in production.

If you open a DRF endpoint in a browser, you do not get raw JSON. You get a styled HTML page with the response, the headers, buttons for other HTTP methods and forms for posting data. This is the browsable API, one of DRF's best-loved features: it lets you explore and test an API without any other tool, and it documents itself while you click around.

This lesson shows how the browsable API works (it is just another renderer), how DRF also describes endpoints through the HTTP OPTIONS method, how to control the names and descriptions people see, and when to switch the HTML renderer off. For full, shareable documentation, combine this with OpenAPI schemas.

The browsable API is a renderer

DRF's default renderers are JSONRenderer and BrowsableAPIRenderer. Content negotiation picks one using the Accept header. A browser asks for text/html first, so it gets the HTML page; curl and API clients ask for JSON (or */*), so they get JSON from the same view. Nothing in your view changes.

Python The same view as JSON and as the browsable HTML page

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.

Output:

TEXT
JSON: 200 application/json Night Trains
HTML: 200 text/html
  page contains 'Book Instance': True
  page contains 'Night Trains': True
  page contains 'OPTIONS': True
  page contains 'DELETE': True
  page contains 'name="title"': True

The HTML page shows the view's name ("Book Instance"), its docstring, the response with status and headers, buttons for the allowed methods, and raw-data or HTML forms generated from the serializer. Login and logout links appear if you include DRF's session login URLs (path("api-auth/", include("rest_framework.urls"))), which is how you test permissioned endpoints in the browser.

OPTIONS: machine-readable self-description

Every DRF view answers an OPTIONS request with a description of itself, produced by a metadata class (SimpleMetadata by default). It lists the view name and description, the renderer and parser media types, and, for views that accept writes, the fields of the serializer with their types, whether they are required and any limits. A front end can use that to build forms.

Python Inspect an endpoint with OPTIONS

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.

Output:

TEXT
name:        Book List
description: Browse and manage the book catalog.
renders:     ['application/json', 'text/html']
parses:      ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data']
POST fields:
  id        integer   required=False read_only=True 
  title     string    required=True  read_only=False max_length=100
  author    string    required=True  read_only=False max_length=60
  genre     string    required=True  read_only=False max_length=20
  price     decimal   required=True  read_only=False
  year      integer   required=True  read_only=False
  in_stock  boolean   required=False read_only=False

Note that actions appears only if the current user is allowed to perform that method, so the metadata respects permissions automatically.

You can add more by subclassing the metadata class and setting DEFAULT_METADATA_CLASS, for example to expose the API version or custom labels. To turn metadata off completely, set the class to None.

Controlling names and descriptions

DRF builds the page title from the class name (BookViewSet becomes "Book List" and "Book Instance") and the description from the docstring. Two settings let you change that: VIEW_NAME_FUNCTION and VIEW_DESCRIPTION_FUNCTION. A common use is to render docstrings as Markdown, or to pull friendlier titles from an attribute. You can also set a class attribute name/description on single views, or use the @action(name=..., description=...) options on viewset actions.

Python Custom view names and descriptions

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.

Output:

TEXT
/status/ -> Service status | REPORT WHETHER THE SERVICE IS UP.
/other/ -> Undocumented | NO DESCRIPTION YET.

In a real project you would put those two functions in a module and give the dotted path in REST_FRAMEWORK (for example "VIEW_NAME_FUNCTION": "myapp.utils.friendly_name"). The demo registers them on its in-memory project module so the lesson can stay in one file.

Customizing the HTML page

The browsable API is built from templates in rest_framework/api.html. To brand it, create templates/rest_framework/api.html in your project that extends the original and overrides a block:

HTML
{% extends "rest_framework/base.html" %}
{% block title %}Bookstore API{% endblock %}
{% block branding %}
  <a class="navbar-brand" href="/">Bookstore API</a>
{% endblock %}

Other useful blocks are userlinks (the login area), breadcrumbs, nav_bar and footer. Bootstrap-based styling is bundled, and DRF serves it through Django's static files.

Turning the HTML renderer off

The browsable API is wonderful in development, but many teams disable it in production:

  • It runs extra queries to render forms (for related fields, each form can load all choices into a <select>), which makes pages slow on big tables.
  • It exposes forms, headers and the structure of your API to anyone with a browser.
  • It is a rendering feature that a JSON-only API does not need.

Set DEFAULT_RENDERER_CLASSES to the JSON renderer only, usually conditioned on DEBUG:

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_RENDERER_CLASSES": ["rest_framework.renderers.JSONRenderer"]
    + (["rest_framework.renderers.BrowsableAPIRenderer"] if DEBUG else []),
}

What does a browser see then? Its Accept header lists */* as a fallback, so it gets JSON, while a client that insists on text/html alone gets an error:

Python A JSON-only view answers HTML-only clients with 406

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.

Output:

TEXT
typical browser  200 application/json {"pong":true}
html only        406 application/json {"detail":"Could not satisfy the request Accept header."}
json             200 application/json {"pong":true}

Documentation habits that pay off

  • Write the docstring for the reader. The first lines of each view docstring appear in the browsable API, in OPTIONS and (with drf-spectacular) in Swagger UI. One clear sentence beats a long essay.
  • Use help_text on model and serializer fields. It flows into the browsable form and into OpenAPI descriptions.
  • Show errors as part of the contract. List which status codes a view can return (400, 401, 403, 404, 429) and what the error body looks like; see exception handling.
  • Keep a changelog. Pair it with versioning so clients know what changed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What decides whether a client receives the browsable HTML page or JSON?

    Browsers ask for text/html, so BrowsableAPIRenderer wins; API clients ask for JSON.
  2. 2. What does an OPTIONS request to a DRF endpoint return?

    SimpleMetadata describes the view, including serializer fields for the methods the user may call.
  3. 3. Which settings change how view names and descriptions are generated?

    Those two settings point to functions that receive the view and return the text.
  4. 4. Why do many teams remove BrowsableAPIRenderer in production?

    The HTML renderer builds forms (sometimes loading many related objects) and offers little value for machine clients.

Summary

  • The browsable API is BrowsableAPIRenderer, chosen by content negotiation when a client prefers text/html.
  • OPTIONS returns view metadata, including serializer field types for writable methods the user may call.
  • Docstrings, help_text and the name/description setting hooks control what people read.
  • Override rest_framework/api.html blocks to brand the page.
  • Use JSON-only renderers in production and generate full documentation with OpenAPI.

Next: Testing DRF APIs