Swagger Integration With Python Django
Below is the step-by-step procedure by which we can integrate swagger with the Django REST framework using Python:
Starting the Project Folder
To start the project use this command
django-admin startproject core
cd core
To start the app use this command
python manage.py startapp home
Now add this app to the ‘settings.py’
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'home',
'rest_framework',
'drf_yasg',
]
install restframework and drf_yasg
pip install drf-yasg
pip install djangorestframework
File Structure
core/settings.py: This code configures Swagger settings for Django REST Framework API, specifying a Bearer token security definition and disabling session-based authentication. Add below code in settings.py for swagger integration:
SWAGGER_SETTINGS = {
'SECURITY_DEFINITIONS': {
'Bearer': {
'type': 'apiKey',
'name': 'Authorization',
'in': 'header'
}
},
'USE_SESSION_AUTH': False,
}
home/swagger.py: Create swagger.py file and add the below code. This code sets up a Swagger schema view for the Django REST Framework API, defining metadata such as title, version, description, terms of service, contact, and license. It allows public access and permits any user to view the schema.
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="My API",
default_version='v1',
description="Test description",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="contact@myapi.local"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
home/urls.py: This Django code imports the admin module for administrative tasks, defines URL patterns for the admin interface and Swagger documentation. The schema_view is imported from a module named swagger, and it’s used to render the Swagger UI for API documentation at the ‘/swagger/’ endpoint with zero caching.
from django.contrib import admin
from django.urls import path
from home.swagger import schema_view
urlpatterns = [
path('admin/', admin.site.urls),
path('swagger/', schema_view.with_ui('swagger',
cache_timeout=0), name='schema-swagger-ui'),
]
Deployment of the Project
Run these commands to apply the migrations:
python3 manage.py makemigrations
python3 manage.py migrate
Run the server with the help of following command:
python3 manage.py runserver
Output
Swagger Integration with Python Django
Integrating Swagger with Django REST Framework can be quite useful for documenting and testing your API. One popular tool for integrating Swagger with Django REST Framework is drf-yasg (Yet Another Swagger Generator). In this article, we will see how to integrate Swagger with the Django REST framework.