3 Steps to make Django document by Swagger UI automatically.

Grassroot Engineer
3 min readAug 14, 2022

--

What is swagger?

This is swagger action haha.

Today I will introduce how to create API doc by automatically using drf-spectacular library so we don’t need to waste of time to write manually anymore, just implement this lib in our Django project then will get API doc is like swagger UI below.

Swagger UI will show all APIs in our project.

We can see payload of each APIs too, so Frontend guys can use this to be reference and communicate.

Let’s get started:

  1. settings.py
# API Docs settingsSPECTACULAR_SETTINGS = {
'TITLE': 'Covid19 API',
'DESCRIPTION': 'Covid19 project API Documents',
'VERSION': '1.0.0',
'SCHEMA_PATH_PREFIX': '/backend/api/*', # เพื่อให้แยกตาม route ใน api_urls จะได้ไม่รวมกันมั่ว
'SERVE_PERMISSIONS': ['rest_framework.permissions.IsAuthenticated'], # ต้อง login ก่อนนะ
'DISABLE_ERRORS_AND_WARNINGS': True,
}
Add spectacular setting in settings.py

2. urls.py

path('schema/', SpectacularAPIView.as_view(), name='schema'),
path('api-docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
Add endpoint’s path in urls.py

3. requirements.in

Don’t forget to install this lib to the project, we can install by pip:

pip install drf-spectacular

or

if we handle all libs in requirements.txt so can add this command in requirements.in

drf-spectacular~=0.16.0

and use command pip-compile to compile from requirements.in to requirements.txt respectively.
# If running in Docker, don’t forget to build image again !!

Add lib in requirements.in

That’s all for settings !!!

Demo of swagger UI

Sample of GET methos api.
Show comments from views.py, model (help-text), serializer.

Anyway sometime if we need to custom the example’s response to show or tell to Frontend guys because don’t need to use the default sample from lib, we can custom like this.

Format of how to custom response to show.

AND

Another thing if we want to specify MIME type for request body, normally we will define request body is like Serializer like this.

I want to show request body is like “upload file” but it’s incorrect and be confused in photo.

So we can specify MIME type like this to solve this issue.

This is solution to define “MIME type” in request body.

Refer to this github issue.

If you think it’s useful for you, just clap your hands 👏 to be encouraged me.

GRASSROOT ENGINEER 😘

--

--