Customize Django REST Framework Browsable API Theme

Learn how to customize the default theme of the Django REST Framework Browsable API. Override templates and blocks for full control over your API

Django REST Framework Browsable API Customization

Customizing the Default Theme

The default look DRF provides for the browsable API is quite appealing on its own. However, if you wish to alter it, DRF offers built-in methods for customization.

The primary step is to create a template file located at templates/rest_framework/api.html. This new template should extend the default rest_framework/base.html template.

{% extends "rest_framework/base.html" %}

Once this base template is set up, you can modify various block components that are inherited from base.html to match your desired styling. This process is similar to how you would customize any other Django template that extends a base template.

  • body - This block controls the entire HTML body of the API view.
  • bootstrap_theme - Use this to override the CSS for the entire Bootstrap theme.
  • bootstrap_navbar_variant - This block allows customization of the Navbar's appearance.
  • branding - Modify the brand component, typically located in the top-left corner of the Navbar.
  • script - Insert custom JavaScript code here.
  • style - Add your custom CSS rules within this block.

These are some of the most commonly used blocks. For a comprehensive list of all available blocks, refer to the official DRF documentation.

Here's an example of how you might customize the branding block:

{% block branding %}
    <a class="navbar-brand" rel="nofollow" href="https://erick.netlify.app">
        Nifled's Blog
    </a>
{% endblock %}

This demonstrates how you can modify any other block to suit your specific needs.

Full API Customization

If the default Bootstrap look doesn't align with your project's aesthetic, you have the option to completely replace the default styling and implement your own custom design. DRF provides a rich context object that you can leverage for this purpose.

The available context variables include:

  • api_settings - Access to various API settings defined in your Django settings.
  • content - The actual content of the API response being rendered.
  • request - The incoming HTTP request object.
  • response - The outgoing HTTP response object.
  • view - The Django REST Framework view that is handling the current request.

A complete enumeration of these context variables can be found in the DRF documentation.

To gain a deeper understanding of how the browsable API is constructed, it's highly recommended to examine the source code of the base.html template within the DRF repository.

Back to Top ↑