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,
models.py
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='')
serializer.py
file,
from rest_framework import serializers
from .models import Snippet
class SnippetSerializer(serializers.ModelSerializer):
class Meta:
model = Snippet
fields = '__all__'
views.py
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
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'))
]
Note that the doc-strings provided in the
views.py
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!
Top comments (1)
Just lovely! The only docs that actually works. You can also add a manual schema by doing: