As per our last post, we can access our APIs in browser. Let’s explore some options to customize the browsable API for our Django REST Framework APIs.
There are two options we will check :
- Customize the output generated by DRF itself.
- Use YASG library (Yet Another Swagger Generator).
You can download the code for this example from here : https://github.com/hpin2019/coding-sessions/tree/master/drf-tutorial-2
Option 1 : Customize DRF Browsable API
Step 1 : Create templates directory in your project
If templates directory does not exist, then create as shown below. and Inside templates create “rest_framework/api.html”.
(venv) $ pwd <your_path>/restapi (venv) $ ls db.sqlite3 manage.py quotes restapi templates (venv) $ find templates/ templates/ templates//rest_framework templates//rest_framework/api.html
Step 2 : Update settings.py
(venv) $ vi restapi/settings.py
Update ‘DIRS’ in Templates list to include newly created templates directory as shown below.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] print(TEMPLATES)
Lot of times, this settings variables do not work for one or other reason. In such cases, just remember that settings.py is another python code only, so you can just print any variable for debugging as show above. When you run server again, it will print the TEMPLATES variable.
Step 3 : Update api.html in templates
Add below code in newly created api.html in templates/rest_framework directory :
{% extends "rest_framework/base.html" %} {% block bootstrap_theme %} <link rel="stylesheet" href="https://bootswatch.com/4/darkly/bootstrap.css" type="text/css"> {% endblock %}
What above code does is, it’s extending rest_framework library’s base.html template file. Then it’s using free darkly theme available at bootswatch.com (you can check here : https://bootswatch.com/darkly/) You can use any bootstrap theme. This will override default bootstrap theme being used by browsable API. After these changes, run the server again and access the api page, it shall look like below.
So this is just theme customization, You can change many more blocks or even override complete output generation also. You can check more details here.
Option 2 : Using YASG Library
YASG, as the name says, is Yet Another Swagger Generator. We will follow this steps to install the library and create our online docs. Check here.
Step 1: Installation
(venv) $ pip install -U drf-yasg (venv) $ pip install packaging (venv) $ pip list Package Version ------------------- ---------- asgiref 3.2.3 certifi 2019.11.28 chardet 3.0.4 coreapi 2.3.3 coreschema 0.0.4 Django 3.0.2 django-filter 2.2.0 djangorestframework 3.11.0 drf-yasg 1.17.1 idna 2.9 inflection 0.3.1 itypes 1.1.0 Jinja2 2.11.1 Markdown 3.1.1 MarkupSafe 1.1.1 packaging 20.1 pip 19.3.1 Pygments 2.5.2 pyparsing 2.4.6 pytz 2019.3 requests 2.23.0 ruamel.yaml 0.16.10 ruamel.yaml.clib 0.2.0 setuptools 45.0.0 six 1.14.0 sqlparse 0.3.0 uritemplate 3.0.1 urllib3 1.25.8 wheel 0.33.6 venv) $
Add drf_yasg in INSTALLED_APPS in settings.py for using it.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'quotes', 'drf_yasg', ]
Step 2 : Update urls.py
Change urls.py as below, newly added code is shown below “#For yasg” comment in each section :
from django.contrib import admin from django.urls import path,include # For yasg from django.urls import re_path from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi from django.views.generic import TemplateView # For yasg schema_view = get_schema_view( openapi.Info( title="Quotes API", default_version='v1', description="Tutorial : Quotes API", terms_of_service="https://www.google.com/policies/terms/", contact=openapi.Contact(email="contact@snippets.local"), license=openapi.License(name="BSD License"), ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('admin/', admin.site.urls), path('api/',include('quotes.urls')), # For yasg re_path(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('openapi/', TemplateView.as_view(template_name="swagger-ui/dist/index.html")), ]
Now run the server again and you can check newly generated browsable swagger API in different formats as below :
- Yaml format : http://127.0.0.1:8000/swagger.yaml
This will download swagger documentation in yaml format. - Json format : http://127.0.0.1:8000/swagger.json
3. OpenAPI format : http://127.0.0.1:8000/swagger/?format=openapi
4. Browsable API : http://127.0.0.1:8000/swagger/
As you can see, all the APIs can be easily accessed. Click on first “GET” api and click on “execute” button, it will fetch the list of all quotes.
Similarly, you can try all other APIs. In next post, we will customize further these API to get more control over the output.
[…] DRF – Browsable API […]