ZMedia Purwodadi

How to Build an API with Django Rest Framework (Full Guide for Beginners in 2025)

Table of Contents
How to Build an API with Django Rest Framework (Full Guide for Beginners in 2025)


Published on www.devmanjoe.com.ng
Category: Web Development | Django | APIs


In today’s tech-driven world, APIs (Application Programming Interfaces) are everywhere — powering mobile apps, websites, fintech solutions, and even your smart fridge. As a Python developer, the Django REST Framework (DRF) gives you one of the most powerful and beginner-friendly ways to build robust, secure APIs fast.

If you're just starting out, or you're building your next backend project, this guide will walk you through everything you need to build a functional API using Django REST Framework in 2025 — with no fluff, only clear code examples, real-world tips, and SEO-rich content to help boost your learning and your blog’s ranking.

Let’s dive in!


🧠 What Is Django REST Framework?

The Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs using Python and Django.

Why developers love it:

  • Easy to use with Django’s ORM

  • Automatic URL routing with viewsets

  • Built-in authentication, permissions, and throttling

  • Powerful serialization and validation features

In short, DRF allows you to turn your Django models into JSON APIs in just a few lines of code.


📦 What We’ll Build

We’ll create a simple but real-world To-Do List API with the following features:

  • Create, Read, Update, Delete (CRUD)

  • RESTful JSON responses

  • Token authentication (optional)

  • Basic permissions

We’ll use:

  • Python 3.11+

  • Django 5+

  • Django REST Framework

  • SQLite (default DB)


✅ Step 1: Install Django and Django REST Framework

Open your terminal and create a virtual environment:

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

Install Django and DRF:

pip install django djangorestframework

Create your project:

django-admin startproject todoapi
cd todoapi
python manage.py startapp tasks

🔧 Step 2: Set Up Django Settings

Edit todoapi/settings.py

Add 'rest_framework' and your app 'tasks' to INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'rest_framework',
    'tasks',
]

Optionally, add this for simple API authentication later:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.AllowAny',  # For dev
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ],
}

🧱 Step 3: Create a Model

Inside tasks/models.py:

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=100)
    completed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

Apply the migrations:

python manage.py makemigrations
python manage.py migrate

🧰 Step 4: Create a Serializer

Inside tasks/serializers.py:

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'

🔁 Step 5: Create Views with Django REST Framework

You can use function-based views, class-based views, or viewsets. We'll use class-based views for clarity.

Inside tasks/views.py:

from rest_framework import generics
from .models import Task
from .serializers import TaskSerializer

class TaskListCreateAPIView(generics.ListCreateAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

class TaskRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

🌐 Step 6: Add URLs

Inside tasks/urls.py:

from django.urls import path
from .views import TaskListCreateAPIView, TaskRetrieveUpdateDestroyAPIView

urlpatterns = [
    path('tasks/', TaskListCreateAPIView.as_view(), name='task-list'),
    path('tasks/<int:pk>/', TaskRetrieveUpdateDestroyAPIView.as_view(), name='task-detail'),
]

Now include it in your todoapi/urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('tasks.urls')),
]

🔎 Step 7: Test Your API

Run the server:

python manage.py runserver

Now open:

  • GET /api/tasks/ → List all tasks

  • POST /api/tasks/ → Create a new task

  • GET /api/tasks/1/ → Retrieve task

  • PUT /api/tasks/1/ → Update task

  • DELETE /api/tasks/1/ → Delete task

Django REST Framework even gives you a beautiful web UI to test APIs.


🔐 Step 8: Add Token Authentication (Optional but Recommended)

To secure your API:

pip install djangorestframework-simplejwt

Update settings:

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    )
}

In your project’s urls.py:

from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns += [
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]

Now users can authenticate with JWT tokens.


🔒 Step 9: Add Permissions

Inside tasks/views.py, add:

from rest_framework.permissions import IsAuthenticated

class TaskListCreateAPIView(generics.ListCreateAPIView):
    permission_classes = [IsAuthenticated]
    ...

This ensures only authenticated users can access your API.


📂 Step 10: Use Postman or Curl for Testing

Here’s how to get a token using Postman:

  1. POST to /api/token/ with:

{
  "username": "admin",
  "password": "yourpassword"
}
  1. Use the returned access token in the header:

Authorization: Bearer <your_token_here>

This way, your frontend or mobile app can securely interact with the backend.


🌍 Use Cases for Django REST Framework APIs

You can build and scale many projects using DRF, such as:

  • Blog API (WordPress replacement)

  • Mobile App Backend (React Native or Flutter)

  • E-Commerce API (products, orders, carts)

  • AI Tools (Python-based ML APIs)

  • Chat Apps, Polls, CRM dashboards


📈 SEO Tips for Django APIs (2025 Edition)

Make your APIs not just functional but search engine friendly:

Tip Why It Matters
Add clear documentation Use Swagger or DRF’s built-in schema views
Use RESTful endpoints Easier to understand and debug
Implement pagination and filtering Helps scale performance
Version your APIs Use /api/v1/ to allow backward compatibility
Handle errors gracefully Custom error messages help frontend + SEO

🚀 Final Tips Before You Launch

Here are a few final things to ensure your API is ready for the real world:

  • ✅ Add API throttling (rate limiting)

  • ✅ Enable HTTPS in production

  • ✅ Use .env files for sensitive data

  • ✅ Deploy using services like Render, Vercel (for frontends), or DigitalOcean


💡 Bonus: What to Learn Next After This API

After mastering this tutorial, level up with:

  • Authentication with Social Logins (Google, GitHub)

  • Custom permissions and roles

  • Caching with Redis or Memcached

  • Swagger / Postman Documentation

  • Connecting React or Vue to your API

  • Dockerizing your Django app


📌 Summary Table

Step What You Did
1 Installed Django + DRF
2 Set up settings and serializers
3 Built views with generics
4 Created RESTful URLs
5 Added authentication (JWT)
6 Added permissions
7 Tested with Postman

🧠 Final Thoughts

APIs are the heart of modern apps, and Django REST Framework makes it simple, scalable, and secure. Whether you're building your own SaaS, working on freelance projects, or launching a startup — mastering DRF is a game-changer.

At www.devmanjoe.com.ng, we’re all about helping you go from beginner to pro with practical tech tutorials, AI guides, and monetization tips.

👉 Bookmark this page
👉 Share this post with your dev friends
👉 Comment below if you’d like a React frontend tutorial to connect to this API

Post a Comment