DRF Introduction - potatoscript/django GitHub Wiki

🌐 REST APIs with Django REST Framework

In today's web development world, APIs (Application Programming Interfaces) are the backbone of many modern applications. They allow different systems to communicate with each other over the web. Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django.

In this tutorial, we’ll guide you step-by-step on how to build a REST API with Django REST Framework, explaining every part in a way that’s easy to understand, even for someone just starting out with programming.


🧩 Step 1: What is Django REST Framework (DRF)?

Django REST Framework (DRF) is an open-source framework for building APIs in Django. It simplifies the process of creating RESTful web services and provides tools for authentication, serialization, views, and more.

Why Use Django REST Framework?

  • Easy to use: DRF simplifies the process of building APIs in Django.
  • Serialization: It handles converting complex data types (like Django models) into JSON format.
  • Authentication & Permissions: DRF provides ready-made solutions for user authentication and controlling access.
  • Browsable API: DRF provides an interactive interface for testing APIs, which is extremely useful during development.

🧩 Step 2: Installing Django REST Framework

To begin using DRF, we need to install it in our Django project. Follow these steps:

  1. Install Django REST Framework:

    In your terminal, run the following command to install DRF using pip:

    pip install djangorestframework
    
  2. Add DRF to INSTALLED_APPS:

    Open the settings.py file in your Django project and add 'rest_framework' to the INSTALLED_APPS list.

    # settings.py
    INSTALLED_APPS = [
        # Other apps
        'rest_framework',
    ]
    

🧩 Step 3: Creating a Basic API

Let's create a simple API for a Book model in Django.

🛠️ Step 3.1: Define the Book Model

First, create a model for a Book in your models.py file.

# models.py
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title

Now, run migrations to create the database table for this model:

python manage.py makemigrations
python manage.py migrate

🛠️ Step 3.2: Create a Serializer

A serializer is responsible for converting your Django models into JSON format (the format used by APIs) and vice versa.

Create a file named serializers.py in your app folder and add the following code:

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

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

This code defines how the Book model should be serialized when it's sent as a response from the API.


🛠️ Step 3.3: Create Views for the API

Next, you need to create views that handle HTTP requests (GET, POST, etc.). DRF provides classes to make this easy. We’ll use the APIView class to create our views.

In your views.py, add the following code:

# views.py
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 BookList(APIView):
    def get(self, request):
        books = Book.objects.all()  # Retrieve all books
        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)

This BookList class provides two methods:

  • GET: Retrieves a list of books.
  • POST: Allows you to create a new book by sending data in the request.

🛠️ Step 3.4: Set Up URLs for the API

Now we need to wire everything together by connecting the view to a URL. In your urls.py, add the following:

# urls.py
from django.urls import path
from .views import BookList

urlpatterns = [
    path('books/', BookList.as_view(), name='book-list'),
]

This creates a URL endpoint at /books/ where you can access the Book API.


🧩 Step 4: Test the API

Now that we have set up the API, we can test it using tools like Postman or cURL. Let’s start with testing it in the browser first:

  1. GET Request: To retrieve all books, visit the URL /books/ in your browser (e.g., http://127.0.0.1:8000/books/).

    You should see a JSON response with all the books in your database:

    [
        {
            "id": 1,
            "title": "Django for Beginners",
            "author": "John Doe",
            "published_date": "2020-01-01"
        },
        {
            "id": 2,
            "title": "Advanced Django",
            "author": "Jane Smith",
            "published_date": "2021-01-01"
        }
    ]
    
  2. POST Request: To create a new book, you can use Postman or a similar tool to send a POST request with the following JSON data:

    {
        "title": "Learning REST API",
        "author": "Lucy Berry",
        "published_date": "2025-05-05"
    }
    

    If the book is created successfully, you will get a 201 Created response with the data you just sent.


🧩 Step 5: Adding Authentication & Permissions

In most real-world applications, you’ll need to control who can access your API. Django REST Framework provides built-in classes for authentication and permissions.

🛠️ Step 5.1: Add Authentication

DRF supports multiple authentication methods. For simplicity, let’s use Token Authentication.

  1. Install Django REST Framework’s Token Authentication:

    pip install djangorestframework-simplejwt
    
  2. Add to INSTALLED_APPS in settings.py:

    INSTALLED_APPS = [
        # other apps
        'rest_framework',
        'rest_framework.authtoken',
    ]
    
  3. Set the Default Authentication Class in settings.py:

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

🛠️ Step 5.2: Permissions

Permissions determine who can access a view. For example, we might want to allow only authenticated users to create a new book.

In views.py, modify the BookList view to add a permission class:

from rest_framework.permissions import IsAuthenticated

class BookList(APIView):
    permission_classes = [IsAuthenticated]  # Only authenticated users can access

    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)

Now, only users who are logged in will be able to POST to the /books/ endpoint.


🧩 Step 6: Browsable API

Django REST Framework provides an awesome feature: a browsable API. This means you can view and interact with your API through a web interface, which is super useful during development.

Once you've set up your API, just visit the URL in your browser (/books/). You’ll see a nice, interactive interface where you can view your data, send requests, and more!


📝 Summary

Feature What Happens
Django REST Framework A toolkit to build APIs in Django quickly and easily.
Serialization Converting Django models into JSON format for API responses.
Views Handling HTTP requests like GET, POST, PUT, DELETE for your API endpoints.
URLs Mapping URLs to specific views to handle incoming requests.
Authentication Restricting access to APIs based on user authentication (e.g., TokenAuth).
Permissions Controlling access to API views based on permissions (e.g., IsAuthenticated).
Browsability Provides a web interface to test and interact with the API.