Django/Swagger/

How to create Django API Documentation using Swagger?

Published on

How to create Django API Documentation using Swagger?
Swagger is one of the most popular tools for developers to document REST APIs. In this article, we will learn how to integrate swagger API with Django rest Framework.

Introduction :

 

Well-written API documentation saves a lot of time and effort spent by the developers to understand the API functionality and Database Model behind the APIs. Swagger Docs provides detailed information about functions, classes, return types, arguments, and more.

In this blog, we are gonna explain how to add API documentation to an API application written using Django. Once the swagger integration with Django Rest Framework is completed, the users will be able to view and test the APIs directly from the browser without any external tools like Postman.

Swagger:

Swagger API is a set of open-source tools built to help programmers develop, design, document, and use REST APIs. The tool is built around the OpenAPI specification and contains three components: Swagger Editor, Swagger UI, and Swagger Codegen.

Django (Django rest Framework):

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django. To know more about relative links click here

Flow Diagram:


flow diagram

Prerequisites:

  • Python

  • Django REST framework

Steps:

Step 1: Install Python.

Python 3.6 or above is needed to create a Django project, therefore please install python and proceed to the next step.

Step 2: Install Django.

Install the Django framework using the following command.

1pip install django

Step 3: Create a Django Project.

Create a Django project using the below command.

1django-admin startproject <your_project_name> 2 3For example: 4django-admin startproject django_rest_swagger

Step 4: Create a Django App:

After creating the Django project, then make the Django app

1python manage.py startapp <your_app_name> 2 3For example: 4django-admin startapp app

A sample screenshot of Django project files is shown below.

Screenshot1

Step 5: Install djangorestframework:

After creating the Django app then install djangorestframework python package by executing the following command.

1pip install djangorestframework

Step 6: Install django-rest-swagger :

After installing the djangorestframework, please install django-rest-swagger package using the following command.

1pip install django-rest-swagger

Step 8: Install drf-yasg:

drf-yasg is a Swagger generation tool implemented without using the schema generation provided by Django Rest Framework. therefore please install the same to proceed further.

1pip install drf-yasg

Step 7: Configure the Django-rest-swagger:

  • In backend/settings.py, add the following snippet:

1INSTALLED_APPS = [ 2    'django.contrib.admin', 3    'django.contrib.auth', 4    'django.contrib.contenttypes', 5    'django.contrib.sessions', 6    'django.contrib.messages', 7    'django.contrib.staticfiles', 8    'app', # Django App 9    'rest_framework_swagger', # Swagger 10    'rest_framework', # Django rest framework 11    'drf_yasg' # Yet Another Swagger generator 12]

Sample code for the /django_rest_swagger/settings.py can be found in the following GitHub URL.

  • In app/models.py create a database table with the Django model.

    1from django.db import models 2 3# Create your models here. 4 5class Product(models.Model): 6 name = models.CharField(max_length=30, null=True,blank=True) 7 price = models.CharField(max_length=40,null=True, blank=True) 8 quantity = models.IntegerField(blank=True, null=True)
  • In your project, go to your /app directory and create a file called serializers.py.


Screenshot2
  • In /app/serializers.py, add the following code.

1from rest_framework import serializers 2from .models import* 3 4class ProductSerializer(serializers.ModelSerializer): 5 class Meta(): 6 model = Product 7 fields = "__all__"

Sample code for the /app/serializers.py can be found in the following GitHub URL.

  • Update the app/views.py file with the following code.

1from rest_framework.response import Response 2from rest_framework import status 3from rest_framework import viewsets 4from .models import * 5from .serializers import* 6# Create your views here. 7 8 9class GetMethod(viewsets.ModelViewSet): 10    queryset = Product.objects.all() 11    serializer_class = ProductSerializer 12 13    def list(self, request, *args, **kwargs): 14        data = list(Product.objects.all().values()) 15        return Response(data) 16 17    def retrieve(self, request, *args, **kwargs): 18        data = list(Product.objects.filter(id=kwargs['pk']).values()) 19        return Response(data) 20 21    def create(self, request, *args, **kwargs): 22        product_serializer_data = ProductSerializer(data=request.data) 23        if product_serializer_data.is_valid(): 24            product_serializer_data.save() 25            status_code = status.HTTP_201_CREATED 26            return Response({"message": "Product Added Sucessfully", "status": status_code}) 27        else: 28            status_code = status.HTTP_400_BAD_REQUEST 29            return Response({"message": "please fill the datails", "status": status_code}) 30 31    def destroy(self, request, *args, **kwargs): 32        product_data = Product.objects.filter(id=kwargs['pk']) 33        if product_data: 34            product_data.delete() 35            status_code = status.HTTP_201_CREATED 36            return Response({"message": "Product delete Sucessfully", "status": status_code}) 37        else: 38            status_code = status.HTTP_400_BAD_REQUEST 39            return Response({"message": "Product data not found", "status": status_code}) 40 41    def update(self, request, *args, **kwargs): 42        product_details = Product.objects.get(id=kwargs['pk']) 43        product_serializer_data = ProductSerializer( 44            product_details, data=request.data, partial=True) 45        if product_serializer_data.is_valid(): 46            product_serializer_data.save() 47            status_code = status.HTTP_201_CREATED 48            return Response({"message": "Product Update Sucessfully", "status": status_code}) 49        else: 50            status_code = status.HTTP_400_BAD_REQUEST 51            return Response({"message": "Product data Not found", "status": status_code}) 52

Sample code for the /app/views.py can be found in the following Github URL.

 

Add the app/urls.py file with the following content

1from .views import * 2from django.urls import path, include 3from rest_framework.routers import DefaultRouter 4 5router = DefaultRouter() 6router.register('data', GetMethod, basename='data') 7urlpatterns = router.urls

An example screenshot of the Django project is shown below.

Screenshot3

Sample code for the app/urls.py file can be found in the following Github URL.

  • Update the django_rest_swagger/urls.py file with the following code.

1"""django_rest_swagger URL Configuration 2 3The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/4.0/topics/http/urls/ 5Examples: 6Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: path('', views.home, name='home') 9Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12Including another URLconf 13 1. Import the include() function: from django.urls import include, path 14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15""" 16from django.contrib import admin 17from django.urls import path,include 18 19from django.conf.urls.static import static 20from rest_framework_swagger.views import get_swagger_view 21from drf_yasg.views import get_schema_view 22from drf_yasg import openapi 23from rest_framework import permissions 24from django.conf import settings 25 26schema_view = get_schema_view( 27 openapi.Info( 28 title="Episyche Technologies", 29 default_version='v1',), 30 public=True, 31 permission_classes=(permissions.AllowAny,), 32) 33 34 35urlpatterns = [ 36 path('admin/', admin.site.urls), 37 path("",include("app.urls")), 38 path('docs/', schema_view.with_ui('swagger', cache_timeout=0),name='schema-swagger-ui'), 39 40] 41 42if settings.DEBUG: 43 urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Sample code for the django_rest_swagger/urls.py file can be found in the following GitHub URL.

 

  • Finally, Run the Django application using the following command.

1python manage.py makemigrations
1python manage.py migrate
1python manage.py runserver

 

A Sample GitHub repo, with all the required configurations, is given below.

Result:

After finishing all the steps mentioned above, please go to the web browser, and try to access the React application (i.e http://localhost:8000/docs/). An example output screenshot is given below.

Results


Results2

Comments