DEV Community

Tek Kshetri
Tek Kshetri

Posted on

9 2

Generate API Docs for Django Rest Framework

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='')
Enter fullscreen mode Exit fullscreen mode

serializer.py 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

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

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 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!

Reference

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

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (1)

Collapse
 
paulwababu profile image
paulsaul621 • Edited

Just lovely! The only docs that actually works. You can also add a manual schema by doing:

from rest_framework.compat import coreapi, coreschema
from rest_framework.schemas import ManualSchema
from rest_framework.schemas import coreapi as coreapi_schema


class HelloView(APIView):
    permission_classes = (IsAuthenticated,) 
    if coreapi_schema.is_enabled():
        schema = ManualSchema(
            fields=[
                coreapi.Field(
                    name="username",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Username",
                        description="Valid username for authentication",
                    ),
                ),
                coreapi.Field(
                    name="password",
                    required=True,
                    location='form',
                    schema=coreschema.String(
                        title="Password",
                        description="Valid password for authentication",
                    ),
                ),
            ],
            encoding="application/json",
        )
    def get(self, request):
        user = request.user
        message = "Hello "+str(user)
        content = {'message': message}
        return Response(content)
Enter fullscreen mode Exit fullscreen mode

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more