Interactive API Documentation with Django Rest Framework and Swagger

Julio Cesar Siles Perez
Django Unleashed
Published in
6 min readAug 9, 2023
Source: https://realpython.com/

In the realm of API development, documentation plays a critical role in helping developers understand and effectively utilize available endpoints and functionalities. In this article, we will delve into how to use Django Rest Framework (DRF) in conjunction with Swagger to create interactive and user-friendly documentation for our APIs.

What is Django Rest Framework?

Django Rest Framework (DRF) stands as a comprehensive toolkit that revolutionizes the way developers construct Web APIs within Django applications. Leveraging the capabilities of Django, DRF equips developers with an array of tools that simplify and enhance the API development process. DRF encompasses vital aspects such as serialization, views, authentication, and documentation, making it a cornerstone of modern API creation.

At its core, DRF introduces the concept of serializers, enabling the transformation of intricate data structures, such as Django model instances, into native Python datatypes. This transformation facilitates seamless rendering into various formats, including JSON and XML, ensuring smooth data exchange between client and server. DRF’s arsenal extends to diverse views and viewsets that streamline the creation of API endpoints. Viewsets come with automatic URL routing and handle fundamental actions like data retrieval and manipulation.

DRF’s impact extends beyond mere data exchange. It fortifies APIs with robust authentication methods, including token-based authentication and OAuth, while its permission system empowers developers to control access to API resources. Notably, DRF collaborates seamlessly with tools like Swagger, a popular API documentation solution. This integration allows developers to craft interactive and intuitive API documentation, fostering understanding and interaction between developers and their APIs.

What is Swagger?

Swagger, an open-source framework, redefines how APIs are designed, built, and documented. Serving as a versatile toolkit, Swagger simplifies the creation of comprehensive and interactive API documentation. Its prowess lies in providing tools to articulate API endpoints, parameters, and responses in a structured manner.

At the heart of Swagger lies the Swagger UI, a web interface that dynamically generates documentation based on API specifications. This interface empowers developers to explore and interact with endpoints directly from their browsers, visualizing operations and responses. Central to Swagger is the OpenAPI Specification (OAS), a machine-readable format that outlines API behavior, authentication, and more.

Incorporating Swagger into development yields manifold advantages. It fosters seamless communication between teams, accelerates developer onboarding, and maintains living documentation that evolves with the API. By adopting Swagger, developers can craft APIs with user-friendly, up-to-date documentation, fostering efficiency and collaboration in API projects.

Benefits of Interactive Documentation

Interactive documentation, epitomized by tools like Swagger, introduces a revolutionary approach to API understanding and utilization. By visually representing API endpoints, parameters, and responses, it enhances clarity and comprehension. This visual mapping reduces complexities, making it easier for developers to grasp an API’s functionalities and interactions.

Moreover, interactive documentation promotes swift onboarding and collaboration. New developers can swiftly familiarize themselves with the API’s intricacies through an intuitive interface, fostering quicker integration into the development process. Additionally, the real-time experimentation feature empowers confident coding and efficient troubleshooting. The interactive nature of the documentation encourages collaboration among teams, reducing communication gaps and fostering a cohesive development environment

Steps to Integrate Swagger with Django Rest Framework

  1. Install Django Rest Framework: Before integrating Swagger, ensure you have Django Rest Framework installed. You can do this using the following command: pip install djangorestframework
  2. Create a new Django Rest Framework and a new app. Use the following commands:
django-admin startproject project_name
python manage.py startapp app_name

3. Install the drf-yasg package for Swagger integration:

pip install -U drf-yasg

4. Configure settings.py in Django:

INSTALLED_APPS = [
...
'django.contrib.staticfiles', # required for serving swagger ui's css/js files
'drf_yasg',
...
]

5. In your project’s urls.py or your app’s 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="Snippets API",
default_version='v1',
description="Test description",
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('swagger<format>/', schema_view.without_ui(cache_timeout=0), name='schema-json'),
path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
...
]

This exposes 4 endpoints:

  • A JSON view of your API specification at /swagger.json
  • A YAML view of your API specification at /swagger.yaml
  • A swagger-ui view of your API specification at /swagger/
  • A ReDoc view of your API specification at /redoc/

6. Access Swagger UI

Run your Django development server using python manage.py runserver and navigate to http://localhost:8000/swagger/ in your browser. You should see the Swagger UI interface displaying your API documentation.

Empty Swagger UI

Customizing the documentation

To explain how to use this package I’ll use a very simple project. First, you must use this in the project’s urls.py :

from django.contrib import admin
from django.urls import path
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from myapp.views import CustomEndpointView

schema_view = get_schema_view(
openapi.Info(
title="Snippets API",
default_version='v1',
description="Test description",
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('swagger<format>/', schema_view.without_ui(cache_timeout=0),
name='schema-json'),
path('swagger/', schema_view.with_ui('swagger',
cache_timeout=0), name='schema-swagger-ui'),
path('redoc/', schema_view.with_ui('redoc',
cache_timeout=0), name='schema-redoc'),
path('admin/', admin.site.urls),
path('custom_endpoint/', CustomEndpointView.as_view(), name='custom-endpoint')
]

And finally this code in the app’s views.py:

from drf_yasg import openapi
from rest_framework.response import Response
from rest_framework.views import APIView
from drf_yasg.utils import swagger_auto_schema


class CustomEndpointView(APIView):
"""
Custom Endpoint Description
"""
@swagger_auto_schema(
operation_description="Endpoint Operation Description",
responses={
200: "Success",
400: "Bad Request",
401: "Unauthorized",
},
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
'field1': openapi.Schema(
type=openapi.TYPE_STRING, description="Field 1 Description"),
'field2': openapi.Schema(
type=openapi.TYPE_STRING, description="Field 2 Description"),
},
required=['field1']
)
)
def post(self, request):
"""
Custom POST Endpoint
"""
return Response("Success")

Using the POST function of the CustomEndpointView class-based view will yield the following results in the Swagger UI:

Swagger UI for CustomEndPoint POST function

And, inside our custom_endpoint we can see the following information

custom_endpoint information

It can be observed that for the POST method, we obtain the groups of fields Parameters and Responses, as well as an overall description of the purpose of this endpoint. Within the Parameters field, we have the required fields for the POST request, as well as the option to perform a test request to showcase its functionality. In the Responses field, we can see the types of responses that the request can generate, along with a description of what each response signifies.

We can do more advanced specifications for our documentation, you can check it on the official site of the package.

Conclusions

In the dynamic landscape of Django API development, Django Rest Framework emerges as an essential toolkit, empowering developers to construct adaptable and potent APIs. This article has highlighted its pivotal role, underscoring its significance in crafting APIs that seamlessly cater to contemporary development demands.

Swagger’s introduction as a documentation tool has revolutionized API documentation. This article has demonstrated how its integration within Django Rest Framework streamlines documentation tasks, fostering lucid comprehension and collaborative development. The fusion of Django Rest Framework’s capabilities with Swagger’s interactive documentation equips developers with an avenue for more efficient and user-friendly API development.

Additional Resources

--

--

Julio Cesar Siles Perez
Django Unleashed

Software Developer | Computer Scientist | Data Scientist | Back-End Developer