DEV Community

ankit-brijwasi
ankit-brijwasi

Posted on

Generate API docs under a minute in Django

Greetings everyone!

In this post, I'll be telling you, how we can generate API docs for any Django rest framework project, in less then a minute!

If that sounds interesting, follow along😁

Step 1: Installing the drf_yasg package

Note: you may find other packages for auto generating your API docs, but most of them are outdated and not maintained, that's why I'll recommend you to stick with drf_yasg

let's start by installing the drf_yasg package into your local development environment

(env) $ pip install drf_yasg
Enter fullscreen mode Exit fullscreen mode

Once the package is installed, include it to the INSTALLED_APPS array, in your settings.py file

# settings.py
...
INSTALLED_APPS = [
    # other packages
    'drf_yasg'
]
...
Enter fullscreen mode Exit fullscreen mode

with this drf_yasg will be installed in your django project

Step 2: Update your root urls file

Once the package is installed, open the root urls.py file of your project

/mydjangoproject
  |-mydjangoproject
  |   |-__init__.py
  |   |-wsgi.py
  |   |-asgi.py
  |   |-urls.py     # <---- This file
  |   |-settings.py
  |-app1
  |-app2
Enter fullscreen mode Exit fullscreen mode

Once it is opened, update it with following code-

# existing imports
...

# import get_schema_view and openapi from drf_yasg
from drf_yasg.views import get_schema_view
from drf_yasg import openapi

# create the schema view
schema_view = get_schema_view(
    openapi.Info(
        title="My Django APIs",
        default_version='v1',
        description="Creating API docs was never this easy!!",
    ),
    public=True
)

# include the schema_view in the urlpatterns
urlpatterns = [
   # existing routes
   ...

   path('docs', schema_view.with_ui('swagger', cache_timeout=0)),
   path('redoc', schema_view.with_ui('redoc', cache_timeout=0)),
]
Enter fullscreen mode Exit fullscreen mode

And it's done, now open 127.0.0.1:8000/docs route and you'll see the swagger page with all of your apis!

If you want the redoc version, just go to the 127.0.0.1:8000/redoc page and redoc api docs will appear there!

Swagger Page

Swagger Page

If you have any problems mention them on the comments😉
Cheers!

Top comments (0)