Document and Test Django APIs with Swagger (Part 1)

Rajesh Joshi - May 18 '21 - - Dev Community

Building APIs with Django Rest Framework is one of the Best Technology to work with, you have so much ways to build an API. But the problem arises when your APIs are not properly documented. But we have Swagger.

INDEX

  • Introduction
  • Setting the Environment
  • Configuring Django
  • Creating Models and Serializers
  • Building APIs
  • Building Documentation
  • Testing our APIs

Introduction

Swagger is one of the widely used API documentation and Testing tool. In this series we are going to use “drf-yasg2” as a Wrapper for our Django / DRF Project.

Following is a Snapshot of API Documentation.
Alt Text

Setting the Environment

Start by creating a fresh Django Project. For the shake of learning we are going to create APIs for a TODO Application, In which users can Create, Read, Update and Delete (CRUD) TODOs.

Create Python Virtual Environment

$ python3 -m venv env
Enter fullscreen mode Exit fullscreen mode

Activate the Virtual Environment

$ source ./env/bin/activate
Enter fullscreen mode Exit fullscreen mode

Now, install modules

$ pip install django djangorestframework drf-yasg2
Enter fullscreen mode Exit fullscreen mode

Create Django project “myapp” in present working directory

$ django-admin startproject myapp .
Enter fullscreen mode Exit fullscreen mode

Create Django app “todos“

$ django-admin startapp todos
Enter fullscreen mode Exit fullscreen mode

Register “todos” and “drf_yasg2” in django’s settings.py (myapp/settings.py)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'rest_framework',
    'drf_yasg2',
    'todos',
]
Enter fullscreen mode Exit fullscreen mode

Also, add the following code block in the same file (settings.py)

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly',
    )
}

SWAGGER_SETTINGS = {
   'SECURITY_DEFINITIONS': {
      'Bearer': {
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header'
      }
   }
}
Enter fullscreen mode Exit fullscreen mode

Edit the project’s urls.py file (myapp/urls.py)

from django.contrib import admin
from django.urls import path, re_path

from drf_yasg2.views import get_schema_view
from drf_yasg2 import openapi

schema_view = get_schema_view(
    openapi.Info(
        title="MyApp Docs.",
        default_version='v1',
    ),
    public=True,
)


urlpatterns = [
    path('admin/', admin.site.urls),

    re_path(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
]
Enter fullscreen mode Exit fullscreen mode

Run Django Migrations

$ python manage.py migrate

Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying auth.0012_alter_user_first_name_max_length... OK
Applying sessions.0001_initial... OK
Enter fullscreen mode Exit fullscreen mode

Run Django Development Server

$ python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Visit http://127.0.0.1:8000/swagger/ You should see blank API Documentation/Testing Web Page

Alt Text

Congratulations! 🎉🎉🎉 You have Successfully generated API Documentation / Testing Page

What’s Next?

In the Next Tutorial, We’ll Create Models, Serializers and Views for our TODO Application.

Thank you
With ❤️ Team Stackless Tech

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .