← Back to Chapters

Installing and Setting Up Django REST Framework

⚙️ Installing and Setting Up Django REST Framework

? Quick Overview

Django REST Framework (DRF) simplifies the process of building Web APIs in Django by providing tools for serialization, handling requests, and managing views.

? Key Concepts

  • APIViews for request handling
  • Serializers for JSON conversion
  • Authentication and permissions
  • Browsable API interface

? Syntax / Theory

DRF integrates with Django by registering itself as an installed app and exposing API-specific classes like APIView and Response.

? Installing Django REST Framework

? View Code Example
# Install Django REST Framework using pip
pip install djangorestframework

⚙️ DRF Project Setup

? View Code Example
# Add DRF to installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]

? DRF Configuration

? View Code Example
# Configure authentication, permissions, and pagination
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}

? Creating an API View

? View Code Example
# Simple APIView returning JSON
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

class HelloWorld(APIView):
    def get(self, request):
        return Response({"message": "Hello, World!"}, status=status.HTTP_200_OK)

? URL Configuration

? View Code Example
# Map API view to URL
from django.urls import path
from .views import HelloWorld

urlpatterns = [
path('hello/', HelloWorld.as_view(), name='hello-world'),
]

▶️ Live Output

? View Code Example
# Run development server
python manage.py runserver
? View Code Example
# JSON response from API
{
"message": "Hello, World!"
}

? Interactive API Simulator

Simulate a client consuming the DRF API Endpoint defined above:

GET
 
Click "Send Request" to fetch data...

? Use Cases

  • Backend APIs for mobile apps
  • REST services for SPAs
  • Microservice architectures

✅ Tips & Best Practices

  • Always use serializers for model data
  • Secure APIs using permissions
  • Test with DRF browsable API

? Try It Yourself

  • Create CRUD APIs using APIView
  • Add token authentication
  • Integrate serializers with models