Understanding and customizing Django REST Framework’s browsable HTML API interface
It is a profoundly erroneous truism… that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them.— Alfred North Whitehead, An Introduction to Mathematics (1911)
API may stand for Application Programming Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested.These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using POST, PUT, and DELETE.
The browsable API is rendered using the BrowsableAPIRenderer class, which is included in the default renderer classes:
rest_framework/renderers.py
class BrowsableAPIRenderer(BaseRenderer): """ HTML renderer used to self-document the API. """ media_type = 'text/html' format = 'api' template = 'rest_framework/api.html' charset = 'utf-8'
By default, the API returns the format specified by the headers. For browsers, this is HTML. You can override the format using the ?format= query parameter:
# View as browsable HTMLhttp://api.example.com/users/# View as JSONhttp://api.example.com/users/?format=json# View as API (browsable API)http://api.example.com/users/?format=api
Browser Extensions: Install JSON viewing extensions for better JSON display:
To add authentication to the browsable API, include routes named "login" and "logout" under the namespace "rest_framework":
from django.urls import include, pathurlpatterns = [ # Your API URLs path('api/', include('myapp.urls')), # REST framework login/logout for browsable API path("api-auth/", include("rest_framework.urls", namespace="rest_framework")),]
The namespace="rest_framework" parameter is required. Without it, the login/logout links won’t appear in the browsable API.
All standard Bootstrap components are available for use in your custom templates.Tooltips:The browsable API uses Bootstrap tooltips. Add the js-tooltip class and title attribute to any element:
<button class="btn btn-primary js-tooltip" title="Click to submit"> Submit</button>