Skip to main content
Django Basics Tutorial
CHAPTER 15 Beginner

Building REST APIs with Django

Updated: May 14, 2026
40 min read

# CHAPTER 15

Building REST APIs with Django

1. Introduction

Modern web development is increasingly decentralized. Often, your backend must serve data not just to web browsers via HTML templates, but to iOS apps, Android apps, and separate React/Vue frontend applications. These clients do not understand HTML; they require raw data formatted as JSON. To achieve this, we build REST APIs. While you can build APIs using vanilla Django, the industry standard is to use the Django REST Framework (DRF). In this chapter, we will install DRF, create Data Serializers, and build API endpoints.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the purpose of a REST API in a decoupled architecture.
  • Install and configure Django REST Framework (DRF).
  • Create a ModelSerializer to convert Python objects to JSON.
  • Build class-based API Views.
  • Test endpoints using the DRF Browsable API interface.

3. Beginner-Friendly Explanation

Imagine you are an author (The Database). You only write books in French (Python Objects). A reader from Japan (An iOS App) wants to read your book. They do not understand French. If you hand them the French book (HTML/Python), they cannot process it. You need a Translator (The Serializer). The Translator takes your French book, translates it into the universal language of English (JSON format), and hands it to the reader. Now, regardless of whether the reader is from Japan (iOS), Brazil (Android), or Canada (React), they can all understand the universal English format. Django REST Framework is the translation agency that automates this entire process.

4. Step 1: Installing Django REST Framework

Open your terminal and install the package:
bash
1
pip install djangorestframework

Register the framework in your core/settings.py file:

python
12345
INSTALLED_APPS = [
    # ... built-in apps
    'blog',
    'rest_framework', # Add DRF here
]

5. Step 2: Creating a Serializer

The Serializer acts exactly like a ModelForm, but instead of converting a Database Model into HTML <input> tags, it converts the Database Model into a JSON string.

Create a new file: blog/serializers.py

python
12345678
from rest_framework import serializers
from .models import Post

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        # Specify the columns to include in the JSON payload
        fields = [&#039;id', 'title', 'content', 'author', 'date_posted']

6. Step 3: Building the API View

Instead of using render() to return an HTML file, we will use DRF's special classes to return the serialized JSON data.

Update blog/views.py:

python
1234567891011121314151617
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Post
from .serializers import PostSerializer

# The @api_view decorator enforces that this route only accepts GET requests
@api_view([&#039;GET'])
def api_post_list(request):
    # 1. Query the database
    posts = Post.objects.all()
    
    # 2. Pass the QuerySet into the Translator. 
    # many=True tells DRF we are translating a list of objects, not just one.
    serializer = PostSerializer(posts, many=True)
    
    # 3. Return the universal JSON data!
    return Response(serializer.data)

7. Step 4: Routing the API

Finally, we connect our new API View to a URL. It is standard practice to prefix API routes with /api/.

Update blog/urls.py:

python
12345678910
from django.urls import path
from . import views

urlpatterns = [
    # Your standard HTML routes...
    path(&#039;', views.home, name='blog-home'),
    
    # The new JSON API endpoint
    path(&#039;api/posts/', views.api_post_list, name='api-post-list'),
]

8. Testing the API

Start your development server. Navigate your browser to http://127.0.0.1:8000/blog/api/posts/.

You will be greeted by the DRF Browsable API. Instead of a raw, ugly wall of JSON text, DRF provides a beautiful, interactive webpage where you can view the JSON payload and even test POST requests directly from the browser without needing tools like Postman!

*The raw output looks like this:*

json
123456789
[
    {
        "id": 1,
        "title": "My First Post",
        "content": "Hello World",
        "author": 1,
        "date_posted": "2026-10-12T14:30:00Z"
    }
]

9. Backend Workflow: Full CRUD with Generic Views

Writing views manually for Create, Read, Update, and Delete takes dozens of lines of code. DRF provides Generic Views that do all the work for you. You can replace the entire view from Step 3 with just three lines of code:
python
123456
from rest_framework import generics

# This automatically handles GET (List) and POST (Create)
class PostListAPIView(generics.ListCreateAPIView):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

*This is the true power of Django REST Framework. Massive functionality with minimal code.*

10. Best Practices

  • API Versioning: Just like in Node.js, always version your APIs. In the master urls.py, route traffic like this: path('api/v1/', include('blog.urls')). This ensures that if you completely redesign the API next year (v2), the legacy mobile apps relying on v1 won't crash.

11. Common Mistakes

  • Forgetting many=True: When querying a list of objects (Post.objects.all()), if you forget to pass the many=True argument to the Serializer, DRF will crash because it expects a single object but received a list.

12. Exercises

  1. 1. Explain the conceptual relationship between a Django ModelForm (used for HTML pages) and a DRF ModelSerializer (used for APIs). How are their primary tasks similar?

13. Coding Challenges

  • Challenge: Using the @apiview(['GET']) decorator, write a detail endpoint apipost_detail(request, pk) that fetches a single post by its Primary Key (pk). Pass the single object to the Serializer (do *not* use many=True), and return the Response.

14. MCQs with Answers

Question 1

What is the primary purpose of a Serializer in the Django REST Framework?

Question 2

When returning data from an API endpoint using Django REST Framework, which object should you use to send the response instead of the standard Django HttpResponse?

15. Interview Questions

  • Q: Explain why Django developers rely on the Django REST Framework (DRF) package instead of simply using Python's built-in json module to serialize data manually.
  • Q: Describe how a decoupled architecture works (e.g., a React frontend communicating with a Django DRF backend). What are the advantages of this approach over traditional server-side rendering (SSR) using Django templates?

16. FAQs

Q: Can I use Django Templates and DRF in the exact same project? A: Yes! This is a hybrid approach. You might render your public blog pages using standard Django HTML Templates for good SEO, while building a separate /api/ section in the same project to feed data to your company's iOS mobile app.

17. Summary

In Chapter 15, we transformed our traditional web server into a modern data provider. By installing the Django REST Framework, we learned how to architect translation layers (Serializers) capable of converting complex database models into universal JSON payloads. We built robust API endpoints using DRF decorators and leveraged the Browsable API interface for seamless testing, paving the way for decoupled frontend integrations like React or mobile apps.

18. Next Chapter Recommendation

APIs and websites face constant threats from the public internet. Proceed to Chapter 16: Django Security Best Practices.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·