Document and Test Django APIs with Swagger (Part 1)
Tags: django, python, tutorial, webdev
Published: 2021-05-18 17:45:31

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gjxgbfa129vr7qarbr5i.png)

## 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

``` bash
$ python3 -m venv env
```

Activate the Virtual Environment

``` bash
$ source ./env/bin/activate
```

Now, install modules

``` bash
$ pip install django djangorestframework drf-yasg2
```

Create Django project “myapp” in present working directory

``` bash
$ django-admin startproject myapp .
```

Create Django app “todos“

``` bash
$ django-admin startapp todos
```

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

``` python
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',
]
```

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

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

SWAGGER_SETTINGS = {
   'SECURITY_DEFINITIONS': {
      'Bearer': {
            'type': 'apiKey',
            'name': 'Authorization',
            'in': 'header'
      }
   }
}
```

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

``` python
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'),
]
```
Run Django Migrations

``` bash
$ 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
```

Run Django Development Server

``` bahs
$ python manage.py runserver
```

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4vsepy82wie0r2ye1i5.png)

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

## What’s Next?
In the [Next Tutorial](https://stackless.tech/document-and-test-django-apis-with-swagger-part-2/), We’ll Create Models, Serializers and Views for our TODO Application.

Thank you
With ❤️ Team [Stackless Tech](https://stackless.tech/)