How to automatically create API Documentation in Django REST Framework?
Writing documentation can be pretty daunting for developers and to be honest, nobody likes writing long explanations, I personally don’t but as we all know, documentation is equally important as writing a properly functioning code. So, there is a pretty simple way of automatically generating documentation, and wait, not only docs but I will also show you how you can create an online playground too for testing out the APIs.
I don’t know about you but for me, Django is the to-go framework for web development so I will show you how you can do so in Django. So, before we get started, you need to have Django and Django REST Framework installed. I am assuming you already have that. Next, you need to install drf-yasg. To do so, simply type the following in the terminal.
pip install drf-yasg
Now, let’s start with the steps.
First, create a new Django project. I am assuming that you already know how to do that.
Next, go to settings.py and add drf_yasg to INSTALLED_APPS
INSTALLED_APPS = [ ... 'drf_yasg', ... ]
Then, go into urls.py and add the driver code for drf_yasg
Now, if you simply run the server and go to localhost:8000/docs, you can see the documentation and if you go to localhost:8000/playground but wait what will the docs show, we have not created any route yet to show the docs. So, let’s quickly create a new app and add a route to it.
First, create an app named demo. I am assuming that you already know to create and add an app to Django settings along with the urls.
Next, go to demo/views.py and add the following code to it.
After this, add this APIView to urls.py to the /email endpoint. That’s it. Now, if you simply run the server on your localhost on port 8000, and go to localhost:8000/docs, you should see the documentation and the playground can be viewed on localhost:8000/playground. It should look something like these.