Django API Documentation with Swagger UI
A good API is well documented. The quality of the documentation affects the user experience and ultimately the level of adoption. Swagger is a cool tool that enable a user to play around with an API to have a good feel of its functionality and its capabilities. In this project, we have created a django rest framework API and integrated it with swagger’s drf_yasg.
The project structure
In the root directory we have myenv directory. It is our virtual environment that will manage the project dependencies and make the project environment reproducible.
$ python -m venv myenv
$ source myenv/bin/activate
$ pip install django
$ django-admin startproject project
Our project is made of 4 apps;
- auths
- ballers
- rest_framework
- drf_yasg
auths
Django comes with an authentication and authorization system that verify user credentials and define the actions each user is allowed to perform. For this purpose the framework has a User model, in this project we have customized the model to create additional fields and to change the default unique identifier from username to email. The auths app through the NewUser model will handle the authentication and permissions for our project.
$ python manage.py startapp auths
ballers
The ballers app has a simple Baller model that contains information about a favourite sportsman. A registered user can view all and add, update and remove players.
$ python manage.py startapp ballers
rest_framework
Django rest framework is a powerful tool for building web APIs, it supports serialization for ORM data sources and has powerful class based views.
$ pip install djangorestframework
drf-yasg
Swagger Ui allow us to create documentations that make it easy for a user to interact with our API. The project/urls.py file is used to customize the schema_view.
$ pip install drf-yasg
Conclusion
In this project we have customized django’s user authentication and built a restful API that is well documented using swagger ui.
Try out the demo here https://drfswagger.herokuapp.com/
To get the code in full https://github.com/stevensimba/drfswagger