DEV Community

Cover image for 🚀 Django REST Framework: Installation & API Documentation Setup
NJOKU SAMSON EBERE
NJOKU SAMSON EBERE

Posted on

🚀 Django REST Framework: Installation & API Documentation Setup

Introduction

Django REST Framework (DRF) is a powerful toolkit for building APIs with Django. In this tutorial, we'll cover how to install DRF and set up interactive API documentation, making your APIs more accessible and developer-friendly.



Prerequisites

Before we get started, ensure you have the following:

  • Python installed (preferably Python 3.8+)
  • Django installed (pip install django)
  • Basic knowledge of Django

Step 1: Install Django REST Framework

To install DRF, open your terminal and run:

pip install djangorestframework 
Enter fullscreen mode Exit fullscreen mode

Once installed, add rest_framework to your INSTALLED_APPS in settings.py:

INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', # Add this line ] 
Enter fullscreen mode Exit fullscreen mode

Step 2: Setting Up API Documentation

1️⃣ Enable Browsable API

DRF provides an interactive browsable API by default. To enable it, ensure your DEFAULT_RENDERER_CLASSES includes:

REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', # Enables interactive UI  ), } 
Enter fullscreen mode Exit fullscreen mode

2️⃣ Install drf-yasg for Swagger & ReDoc Documentation

To generate API documentation, install drf-yasg:

pip install drf-yasg 
Enter fullscreen mode Exit fullscreen mode

Then, update your urls.py:

from django.urls import path, re_path from rest_framework import permissions from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="My API", default_version='v1', description="API documentation", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), ] 
Enter fullscreen mode Exit fullscreen mode

Step 3: Run and Test the API Docs

Start the Django development server:

python manage.py runserver 
Enter fullscreen mode Exit fullscreen mode

Now, visit:

Conclusion

You have successfully installed Django REST Framework and set up interactive API documentation. This setup will help developers explore your API seamlessly.

📌 Watch the full video tutorial here: https://youtu.be/PkMnVFwEEmU

💬 Have any questions? Drop them in the comments!

🚀 Keep Building! 🚀


Tags:

Django #DjangoRestFramework #Python #APIDevelopment #RESTAPI #BackendDevelopment #WebDevelopment

Top comments (0)