Browsable API
One of the defining features of Django REST Framework is its Browsable API. When an API endpoint is accessed from a web browser (as indicated by the Accept: text/html header), DRF renders the response using a beautifully formatted, interactive HTML interface.
This allows developers, clients, and partners to easily explore, interact with, and test the API directly in their browser without needing external tools like Postman or curl.
How It Works
The Browsable API is provided by the BrowsableAPIRenderer. This renderer is included by default in DRF's DEFAULT_RENDERER_CLASSES setting.
When DRF detects that the request wants an HTML response, the BrowsableAPIRenderer takes the API data (which would normally be output as JSON) and renders it using a Django template to create the web interface.
Key Features
- Interactive Forms: For endpoints that support
POST,PUT, orPATCHmethods, the Browsable API automatically generates HTML forms based on the view's serializer. You can submit data directly from the browser. - Authentication Integration: The interface respects your configured authentication classes. If you are logged in to the Django admin, your session will automatically apply to the Browsable API.
- Pagination & Filtering: If your view has pagination or filtering configured, the Browsable API will display the appropriate controls and links.
- Documentation: The docstring of your view class or function is automatically extracted and displayed as the description for the endpoint in the UI.
Customizing the Browsable API
You can customize the appearance and behavior of the Browsable API in several ways.
Customizing the Theme
You can change the color scheme or logo of the Browsable API by overriding the default CSS or extending the base templates.
Create a file named rest_framework/api.html in your project's template directory:
{% extends "rest_framework/base.html" %}
{% block branding %}
<a class="navbar-brand" href="/">My Custom API</a>
{% endblock %}Disabling the Browsable API
In a production environment, you might want to disable the Browsable API to reduce overhead or prevent users from accessing the interactive forms.
You can do this by removing BrowsableAPIRenderer from your global DEFAULT_RENDERER_CLASSES setting:
REST_FRAMEWORK = {
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
# 'rest_framework.renderers.BrowsableAPIRenderer', <- Removed
]
}Or you can disable it per-view by defining the renderer_classes attribute directly on the view:
from rest_framework.renderers import JSONRenderer
from rest_framework.views import APIView
class ProductionView(APIView):
renderer_classes = [JSONRenderer]
# ...