Django REST Framework Introduction

Building powerful Web APIs with Django

🚀 What is Django REST Framework?

Django REST Framework (DRF) is a powerful toolkit for building Web APIs in Django. It provides features like serialization, authentication, and browsable API interfaces for rapid development.


# Simple API view example
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def hello_api(request):
    return Response({'message': 'Hello from DRF!'})
                                    

Output:

{
    "message": "Hello from DRF!"
}

Key DRF Features

🔄

Serialization

Convert complex data to JSON

class BookSerializer(ModelSerializer):
    class Meta:
        model = Book
🔐

Authentication

Built-in auth methods

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}
🌐

Browsable API

Interactive web interface

# Automatically generated
# Visit /api/ in browser

ViewSets

Reduce code duplication

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

🔹 Installation

Install Django REST Framework using pip and add it to your Django project:

# Install DRF
pip install djangorestframework

# Install Django if not already installed
pip install django

Add to 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
]

🔹 Your First API

Create a simple API endpoint that returns data in JSON format:

# views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def book_list(request):
    books = [
        {'id': 1, 'title': 'Python Basics', 'author': 'John Doe'},
        {'id': 2, 'title': 'Django Guide', 'author': 'Jane Smith'},
    ]
    return Response(books)
# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('api/books/', views.book_list, name='book-list'),
]

Output (GET /api/books/):

[
    {
        "id": 1,
        "title": "Python Basics",
        "author": "John Doe"
    },
    {
        "id": 2,
        "title": "Django Guide",
        "author": "Jane Smith"
    }
]

🔹 API Request Methods

DRF supports all standard HTTP methods for building RESTful APIs:

@api_view(['GET', 'POST'])
def book_list(request):
    if request.method == 'GET':
        # Return list of books
        return Response({'books': []})
    
    elif request.method == 'POST':
        # Create new book
        title = request.data.get('title')
        return Response({'message': f'Created: {title}'}, status=201)

Common HTTP Methods:

  • GET: Retrieve data
  • POST: Create new resource
  • PUT: Update entire resource
  • PATCH: Partial update
  • DELETE: Remove resource

🔹 Basic Project Structure

Organize your DRF project with this recommended structure:

myproject/
├── myproject/
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── api/
│   ├── models.py
│   ├── serializers.py
│   ├── views.py
│   └── urls.py
└── manage.py

🧠 Test Your Knowledge

What does DRF stand for?