How to generate Swagger documentation for Rest APIs in Django Rest Framework?
How to auto generate Rest API Docs in Django Rest Framework with drf-yasg?
Unlike our last blog, where we used DRF’s Open API schema generation to auto-generate the API documentation, in this blog, we are going to use drf-yasg
to auto-generate the Swagger documentation for our Rest APIs created with Django Rest Framework.
Installation:
The simplest way to install drf-yasg
is to use pip
pip install -U drf-yasg
After the successful installation, you just need to add drf_yasg
package in your INSTALLED_APPS
list of settings.py
file.
# settings.py
...
INSTALLED_APPS = [
...
'drf_yasg',
]
...
Integration with Django:
To integrate and auto-generate the Swagger documentation in your Django project, let’s add this code to our root urls.py
file.
# project/urls.py
...
from django.urls import re_path
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
schema_view = get_schema_view(
openapi.Info(
title="DevJunction API",
default_version="v1",
description="DevJunction API",
terms_of_service="<https://www.google.com/policies/terms/>",
contact=openapi.Contact(email="contact@devjunction.in"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=[permissions.IsAdminUser], # You can add your own permissions
)
urlpatterns = [
# For the OpenAPI documentation
re_path(
r"^swagger(?P<format>\\.json|\\.yaml)$",
schema_view.without_ui(cache_timeout=0),
name="schema-json",
),
re_path(
r"^api/docs/swagger/$",
schema_view.with_ui("swagger", cache_timeout=0),
name="schema-swagger-ui",
),
re_path(
r"^api/docs/redoc/$",
schema_view.with_ui("redoc", cache_timeout=0),
name="schema-redoc",
),
...
]
Above urls.py
will expose 4 endpoints:
A
JSON
view of your API specification at/api/docs/swagger.json
A
YAML
view of your API specification at/api/docs/swagger.yaml
A
swagger-ui
view of your API specification at/api/docs/swagger/
A ReDoc view of your API specification at
/api/docs/redoc/
Yuhuuu! You did it, just run your project and open your browser and go to any of the above endpoints to check out the auto-generated API documentation.
If you want to go into the depth of the drf-yasg
library, you can visit the Official GitHub repository or Official documentation.
Any thoughts? Write it down in the comments.
For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.