3 Steps to make Django document by Swagger UI automatically.
What is swagger?
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.
We can see payload of each APIs too, so Frontend guys can use this to be reference and communicate.
Let’s get started:
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,
}
2. urls.py
path('schema/', SpectacularAPIView.as_view(), name='schema'),
path('api-docs/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'),
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 !!
That’s all for settings !!!
Demo of swagger UI
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.
AND
Another thing if we want to specify MIME type
for request body, normally we will define request body is like Serializer like this.
So we can specify MIME type
like this to solve this issue.
Refer to this github issue.
If you think it’s useful for you, just clap your hands 👏 to be encouraged me.
GRASSROOT ENGINEER 😘