DEV Community


Generate API Docs for Django Rest Framework

Tek Bahadur Kshetri
I am a Geomatics engineer working as a research associate in Geoinformatics Center (GIC), AIT, Thailand. I am mainly passionated for spatial data analysis and web-GIS development.
・1 min read

In this blog, I will show you how to generate the documentation of your Django API in 2 min. Let's start,

There are many tools available to generate the docs for REST API but I prefer something simple and lucid.

For this example, I have created the snippet model with following settings, file,

from django.db import models

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
Enter fullscreen mode Exit fullscreen mode file,

from rest_framework import serializers
from .models import Snippet

class SnippetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Snippet
        fields = '__all__'
Enter fullscreen mode Exit fullscreen mode file,

from rest_framework import viewsets
from .models import Snippet
from .serializer import SnippetSerializer

class SnippetViewSet(viewsets.ModelViewSet):
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.
    queryset = Snippet.objects.all()
    serializer_class = SnippetSerializer

Enter fullscreen mode Exit fullscreen mode

Let's provide the URL endpoint for our API documentation,

from .views import SnippetViewSet
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from rest_framework.documentation import include_docs_urls

router = DefaultRouter()
router.register(r'snippet', SnippetViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
    path('docs/', include_docs_urls(title='Snippet API'))
Enter fullscreen mode Exit fullscreen mode

Note that the doc-strings provided in the file will be used for our documentation so please provide as much information as you can.

Now your API documentation can be found in http://localhost:8000/docs.

Happy coding!


  1. Build a RESTAPI using nested serializers in Django-Rest-Framework: medium

Discussion (0)