Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What is Django REST Framework and why should you use it for API development? Django REST Framework क्या है और API development के लिए इसे क्यों use करना चाहिए?

Answer

Django REST Framework (DRF) is a powerful, flexible toolkit for building REST APIs with Django. It provides serializers for data validation, class-based views, authentication, permissions, and built-in browsable API interface. Reduces boilerplate code dramatically.

FeatureBenefitExample
SerializersAutomatic data validation and conversionModelSerializer auto-generates from model
ViewSetsReusable view logic for CRUDOne ViewSet replaces 5+ view functions
AuthenticationMultiple auth methods built-inToken, JWT, Session auth
PermissionsFine-grained access controlObject-level, global-level permissions
Browsable APIInteractive API documentationTest endpoints directly in browser
// Install DRF
pip install djangorestframework

// Add to INSTALLED_APPS (settings.py)
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'rest_framework',  # Add this
    'myapp',
]

// Configure DRF (settings.py)
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 20,
}

// models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    published_date = models.DateField()
    created_at = models.DateTimeField(auto_now_add=True)

// serializers.py
from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'price', 'published_date', 'created_at']
        read_only_fields = ['id', 'created_at']

// views.py - APIView (Traditional)
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Book
from .serializers import BookSerializer

class BookListAPIView(APIView):
    def get(self, request):
        books = Book.objects.all()
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)
    
    def post(self, request):
        serializer = BookSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

// views.py - ViewSets (Recommended)
from rest_framework import viewsets

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

// urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
]

// API Endpoints Generated Automatically:
// GET /api/books/ - List all books
// POST /api/books/ - Create new book
// GET /api/books/{id}/ - Retrieve specific book
// PUT /api/books/{id}/ - Update book
// PATCH /api/books/{id}/ - Partial update
// DELETE /api/books/{id}/ - Delete book

// Why DRF is Better than Raw Django:
// 1. Less boilerplate - ViewSets handle CRUD automatically
// 2. Automatic serialization - JSON/XML conversion handled
// 3. Validation - Serializers validate data automatically
// 4. Authentication - Multiple methods out of box
// 5. Permissions - Fine-grained access control
// 6. Documentation - Auto-generated API docs
// 7. Pagination - Built-in pagination support
// 8. Filtering/Search - Easy to add filtering
// 9. Throttling - Rate limiting built-in
// 10. Testing - Easy to test API endpoints

DRF एक powerful toolkit है REST APIs बनाने के लिए Django के साथ। Serializers, ViewSets, Authentication, और Permissions built-in हैं।

Was this answer clear?