Learn Django Β· 11/13

Django REST Framework (DRF): Building APIs πŸ”Œ

7 min read

Before we start building, let's get our environment set up. We strictly follow the official Django REST Framework (DRF) documentation for installation.

πŸ› οΈ Installation & Setup

Requirements (as of latest DRF versions):

  • Python 3.10+
  • Django 4.2, 5.0, 5.1, or 5.2

Step 1: Install via pip
Open your terminal and run:

bash
pip install djangorestframework

Step 2: Add to your Django project
Navigate to your project's settings.py file and add 'rest_framework' to your INSTALLED_APPS:

python
INSTALLED_APPS = [
    # ... other apps
    'rest_framework',
]

That is it! DRF is now installed and ready to use.


1. What is an API and Why Add DRF to Django?

Definition

An API (Application Programming Interface) is a set of rules and protocols that allows different software applications to communicate with each other. Specifically, a Web API allows a client (like a web browser or mobile app) to request data from a server over HTTP, and the server returns that data in a universally readable format, usually JSON (JavaScript Object Notation).

The Problem

Out of the box, Django is fantastic at rendering HTML pages. When a user requests a URL, Django fetches data from the database, injects it into an HTML template, and sends the full webpage back to the browser.

However, modern software does not work this way. What if your frontend is built with React? What if you are building an iOS or Android app? A mobile app does not know what to do with a clump of HTML. It has its own UI components. It just needs the raw data.

The Solution

We use an API to return raw data instead of HTML. While pure Django can return JSON using JsonResponse, doing this for hundreds of complex database models, handling user authentication, parsing incoming data, and handling error messages quickly becomes an absolute nightmare.

Django REST Framework (DRF) is a powerful toolkit built on top of Django that handles all of this heavy lifting. It converts Django's data into JSON efficiently and provides standard ways to handle routing, authentication, and permissions.

Real-Life Scenario πŸ•

Imagine you are running a pizza shop (the server).

In traditional Django, a customer walks in, asks for a pizza, and you hand them a fully furnished dining room table with the pizza nailed to it (the HTML page).

In the modern API world, the customer is eating at home (React, iOS app). They call you on the phone (the HTTP Request). They just want the pizza in a standard cardboard box (JSON data). DRF is the highly efficient assembly line that safely boxes up your pizzas and hands them to the delivery driver.


2. Serializers: Translating Complex Models to JSON

Definition

A Serializer is a component that converts complex data types, such as Django Models or QuerySets, into native Python data types that can easily be rendered into JSON, XML, or other content types. They also handle the reverse process (Deserialization), validating incoming parsed data before saving it back to the database.

The Problem

Databases store information in tables. Django represents these tables as Python Objects (Models). If you try to send a Django Pizza object directly over the internet, the network will crash and burn with a TypeError. The internet speaks in text (JSON), and JSON has no idea what a Python object is.

The Solution

Serializers act as the official translators of your application. They map the complex properties of your Django Models into a simple dictionary format that translates perfectly into JSON.

Real-Life Scenario 🧳

Think of serialization like packing a suitcase for a flight. Your Django Model is a sprawling, bulky wardrobe. You cannot just throw your entire closet onto an airplane. A Serializer neatly folds your clothes (data) and packs them tightly into a standard suitcase (JSON) so they can travel across the internet. When the suitcase reaches its destination, the receiving app unpacks it (Deserialization).

Industry Practice: ModelSerializer

In the industry, you will rarely write manual serializers from scratch. You will use ModelSerializer, which automatically generates fields based on your Django models.

python
# models.py
from django.db import models

class Pizza(models.Model):
    name = models.CharField(max_length=100)
    cheese_type = models.CharField(max_length=50)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    is_vegetarian = models.BooleanField(default=False)

# serializers.py
from rest_framework import serializers
from .models import Pizza

class PizzaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pizza
        # Industry standard: Explicitly list fields instead of using '__all__' for security
        fields = ['id', 'name', 'cheese_type', 'price', 'is_vegetarian'] 

3. Function-Based API Views vs. Class-Based API Views

Definition

Views are the core logic handlers in Django. When a request hits a specific URL endpoint, a view processes the incoming request, queries the database, uses the serializer, and returns the Response. DRF offers two ways to write these: Function-Based Views (FBVs) and Class-Based Views (CBVs).

The Problem

You need to handle different HTTP methods (GET to read data, POST to create data, PUT/PATCH to update data, DELETE to remove data) on a single URL. Doing this with standard if/else logic in Python can result in massive, unreadable blocks of spaghetti code.

The Solution

DRF provides wrappers (@api_view for functions) and base classes (APIView for classes) that route the HTTP methods cleanly and handle request parsing automatically.

1. Function-Based Views (FBVs)

FBVs use the @api_view decorator. They are explicit and easy to read, making them great for small, highly custom logic.

python
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Pizza
from .serializers import PizzaSerializer

@api_view(['GET', 'POST'])
def pizza_list(request):
    if request.method == 'GET':
        pizzas = Pizza.objects.all()
        serializer = PizzaSerializer(pizzas, many=True) # many=True because it's a list
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = PizzaSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

2. Class-Based Views (CBVs) & Generics

In real-world industry applications, writing out the exact same GET and POST logic for Pizzas, Customers, Orders, and Ingredients violates the DRY (Don't Repeat Yourself) principle.

DRF provides Generic Class-Based Views that abstract away the boilerplate code entirely.

python
from rest_framework import generics
from .models import Pizza
from .serializers import PizzaSerializer

# This does the EXACT same thing as the function above, but in 4 lines of code.
class PizzaListCreateAPIView(generics.ListCreateAPIView):
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer

4. ViewSets and Routers: Automating API Endpoints

Definition

A ViewSet is a type of class-based view that combines the logic for a set of related operations (like creating, reading, updating, and deleting) into a single class. A Router is a DRF utility that automatically generates the URLs for a ViewSet.

The Problem

Even with Generic CBVs, you still have to write multiple classes per database model:

  1. PizzaListCreateAPIView (for /pizzas/)
  2. PizzaRetrieveUpdateDestroyAPIView (for /pizzas/<id>/)

And then you must manually map every single one of these views to URLs in urls.py. As your app grows to 50+ models, maintaining the urls.py file becomes a massive chore.

The Solution

ModelViewSet handles all standard database operations (Create, Read, Update, Delete) automatically. You combine it with a DefaultRouter which dynamically wires up the URLs for you.

Real-Life Scenario πŸ‘”

Imagine hiring a manager for your pizza shop. Instead of hiring five different employees and individually teaching one to take orders, one to read recipes, one to update the menu, and one to throw away burnt pizzas (Generic Views + manual URLs), you hire one highly efficient General Manager (ViewSet). You hand them a standard rulebook (Router), and they automatically organize all operations without you having to micromanage every task.

Industry Practice Code Example

This is the most frequent pattern you will see in professional DRF codebases for standard CRUD (Create, Read, Update, Delete) APIs.

python
# views.py
from rest_framework import viewsets
from .models import Pizza
from .serializers import PizzaSerializer

class PizzaViewSet(viewsets.ModelViewSet):
    """
    This single class automatically provides:
    - GET /pizzas/ (List all)
    - POST /pizzas/ (Create new)
    - GET /pizzas/{id}/ (Retrieve one)
    - PUT /pizzas/{id}/ (Update one)
    - DELETE /pizzas/{id}/ (Delete one)
    """
    queryset = Pizza.objects.all()
    serializer_class = PizzaSerializer

Now, we wire it up automatically using a Router:

python
# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import PizzaViewSet

# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r'pizzas', PizzaViewSet, basename='pizza')

# The API URLs are now determined automatically by the router.
urlpatterns = [
    path('api/', include(router.urls)),
]

With less than 15 lines of code total between your View, Serializer, and URLs, you have a fully functional, production-ready, highly scalable API endpoint. That is the magic of Django REST Framework! ✨


πŸ“š References & Further Reading

For deeper dives into the concepts discussed, always refer to the official documentationβ€”it is considered one of the best-written docs in the Python ecosystem:

Challenge

You are building an API for an e-commerce platform. Your task is to create a full set of CRUD (Create, Read, Update, Delete) endpoints for a Product model using Django REST Framework's most efficient and abstract tools.

Assume the following Django model has been defined for you:

python
class Product(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)
    in_stock = models.BooleanField(default=True)

Your Tasks:

  1. Create a Serializer: Define a ProductSerializer class that inherits from serializers.ModelSerializer. Configure its inner Meta class to automatically handle all fields from the Product model.

  2. Create a ViewSet: Define a ProductViewSet class that inherits from viewsets.ModelViewSet. This ViewSet should manage all CRUD operations for the Product model. You must set the queryset to retrieve all Product objects and link the serializer_class to the ProductSerializer you created.

  3. Configure Routing: Instantiate routers.DefaultRouter. Register your ProductViewSet with this router using products as the URL prefix. Finally, assign the router's generated URL patterns to a variable named urlpatterns.

Expected result

Your final code should contain the following three components:

  1. A class named ProductSerializer that inherits from serializers.ModelSerializer.

    • It must contain an inner class named Meta.
    • The Meta class must have a model attribute set to Product.
    • The Meta class must have a fields attribute set to the string '__all__'.
  2. A class named ProductViewSet that inherits from viewsets.ModelViewSet.

    • It must have a queryset attribute assigned the value Product.objects.all().
    • It must have a serializer_class attribute assigned the value ProductSerializer.
  3. A block of code for routing:

    • An instance of routers.DefaultRouter must be created and assigned to a variable (e.g., router).
    • The register method of the router instance must be called with 'products' and ProductViewSet as arguments.
    • A variable named urlpatterns must be declared and assigned the value of router.urls.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.