Python Django Full Tutorial For Beginners: Master API Development

By admin December 21, 2025 8 min read

Introduction

Welcome to Halogenius Ideas! If you have been looking to level up your backend development skills, you have arrived at the right place. Building APIs (Application Programming Interfaces) is a superpower in the modern tech landscape. It allows your applications to talk to each other, powers mobile apps, and enables the complex web of services we use every day.

In this comprehensive guide, we are going to walk through a complete Python Django API Development roadmap. Whether you are a complete beginner or an intermediate developer looking to sharpen your skills with the Django Rest Framework (DRF), this guide is tailored for you. We will cover everything from setting up your environment to implementing advanced authentication.

This article serves as a companion guide to our full 7-hour video course. For the complete visual experience, we highly recommend you watch the full tutorial here.

Prerequisites

Before we dive into the code, there are a few things you need to have in place. Don’t worry, the barrier to entry is low.

  • Basic Python Knowledge: You should understand variables, functions, and loops. If you need a refresher, check out our Python crash course on the YouTube channel.
  • Basic Command Line usage: You will need to use the terminal (Command Prompt on Windows or Terminal on Mac/Linux) to run commands.
  • A Text Editor: We recommend VS Code for its excellent Python support.

Installing Python and Your Text Editor

First, ensure Python is installed on your machine. Visit python.org and download the latest version (3.10 or higher is recommended). During installation on Windows, make sure to check the box that says “Add Python to PATH”. This is crucial for running Python from your terminal.

Next, install VS Code. It is lightweight and has a massive ecosystem of extensions. Once installed, search for the “Python” extension by Microsoft and install it.

Creating a Virtual Environment

It is best practice to keep your project dependencies isolated. We do this using a virtual environment.

Open your terminal, navigate to your desired folder, and run the following:

# Create the virtual environment
python -m venv env

# Activate the virtual environment
# Windows:
env\Scripts\activate

# Mac/Linux:
source env/bin/activate

Once activated, your terminal prompt should show (env) at the beginning.

Installing Django and Django Rest Framework

With our environment ready, we need to install the stars of the show: Django and Django Rest Framework. We will also install openpyxl for handling Excel files later on.

pip install django djangorestframework openpyxl

Creating The Project

Now, let’s scaffold our Django project. In Django, a “project” is the overall container, and “apps” are the functional components inside it.

# Create the project named 'backend'
# The '.' at the end installs it in the current directory.
# If you omit it, it creates a new subfolder.
django-admin startproject backend .

Generating Requirements.txt file

To ensure other developers (or your future self) can replicate your environment, freeze your installed packages into a requirements file.

pip freeze > requirements.txt

Verifying Django Installation

Let’s make sure everything is working. Run the development server:

python manage.py runserver

Open your browser and go to http://127.0.0.1:8000/. You should see the famous Django rocket ship, indicating a successful installation.

Installing Django App

We need an app to hold our API logic. Let’s create an app called api.

python manage.py startapp api

Crucial Step: You must register this new app and the REST framework in your project settings.

Open backend/settings.py and modify INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third party apps
    'rest_framework',

    # My apps
    'api',
]

File Organization

Django follows a strict MVT (Model-View-Template) architecture, though for APIs, we focus on Models, Views, and Serializers. Your api folder should now contain models.py, views.py, and admin.py. We will soon create a new file called serializers.py.

Django Models

Models define the structure of your database. For this tutorial, let’s create a robust Student model that includes fields for gender, email, and phone number.

Open api/models.py:

from django.db import models

class Student(models.Model):
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )

    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    phone_number = models.CharField(max_length=15)
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    date_joined = models.DateField(auto_now_add=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

After defining the model, apply the changes to the database:

python manage.py makemigrations
python manage.py migrate

Importing data from Django to Excel DB

One powerful feature covered in our video tutorial is handling Excel files using openpyxl. This is useful if you need to seed your database from an existing Excel sheet or export data.

Here is a snippet of how you might script a data import. You would typically run this in a management command or the Django shell.

import openpyxl
from api.models import Student

def import_students_from_excel(file_path):
    wb = openpyxl.load_workbook(file_path)
    sheet = wb.active

    for row in sheet.iter_rows(min_row=2, values_only=True):
        # Assuming columns: First Name, Last Name, Email, Phone, Gender
        Student.objects.create(
            first_name=row[0],
            last_name=row[1],
            email=row[2],
            phone_number=row[3],
            gender=row[4]
        )
    print("Data imported successfully!")

JSON; Javascript Object Notation

APIs communicate primarily using JSON. It allows us to transfer data in a readable format between the server (Django) and the client (React, Vue, or Mobile App).

A simple JSON object looks like this:

{
  "firstName": "John",
  "lastName": "Doe",
  "email": "john@example.com"
}

Writing your first API View

Before using DRF’s magic, it helps to understand how a basic view works. In api/views.py, you can create a function that returns a JSON response.

from django.http import JsonResponse

def home(request):
    data = {
        "message": "Welcome to Halogenius Ideas API",
        "status": 200
    }
    return JsonResponse(data)

Function-Based Views and Class-Based Views

Django allows two ways to write views. Function-Based Views (FBV) are explicit and easy to read for beginners. Class-Based Views (CBV) are more powerful and reusable, ideal for large applications.

In DRF, we often use the @api_view decorator for functions or inherit from APIView for classes.

Implementing a CRUD system using DRF

CRUD stands for Create, Read, Update, Delete. These are the four basic operations of persistent storage.

Serializers

To send our Student model data over the network as JSON, we need to “serialize” it. Create a new file api/serializers.py.

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id', 'first_name', 'last_name', 'email', 'gender']

Adding Fields to Serializers

If you need to add custom fields that aren’t in your model (like a full name field computed on the fly), serializers make this easy:

from rest_framework import serializers
from .models import Student

class StudentSerializer(serializers.ModelSerializer):
    full_name = serializers.SerializerMethodField()

    class Meta:
        model = Student
        # Add 'full_name' to the fields list
        fields = ['id', 'full_name', 'email', 'gender']

    def get_full_name(self, obj):
        return f"{obj.first_name} {obj.last_name}"

Filtering Queryset Data

DRF allows you to filter data easily. You can filter based on the current user or URL parameters. For example, to find all male students:

queryset = Student.objects.filter(gender='M')

Pagination in DRF

When you have thousands of records, you don’t want to send them all at once. Pagination splits the response into pages. Add this to your settings.py:

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

Generic API Views and Mixins

Instead of writing raw code for every view, DRF provides Generic Views and Mixins. These are pre-built classes that handle common patterns like listing items or creating a new one.

from rest_framework import generics
from .models import Student
from .serializers import StudentSerializer

class StudentListCreateView(generics.ListCreateAPIView):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

Viewsets and Routers

For the ultimate efficiency, ViewSets combine logic for a set of related views. Coupled with Routers, they automatically generate URLs for you.

In views.py:

from rest_framework import viewsets

class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class = StudentSerializer

In urls.py:

from rest_framework.routers import DefaultRouter
from .views import StudentViewSet

router = DefaultRouter()
router.register('students', StudentViewSet)

urlpatterns = router.urls

How to Create New Users over API

Creating users is slightly different because of password hashing. You should use a serializer that overrides the create method to use create_user instead of standard creation, ensuring the password is encrypted.

Authentication and Permissions/Authorization in DRF

Authentication verifies who you are. Authorization verifies what you are allowed to do. DRF handles both elegantly.

Basic Authentication vs. Session Authentication

Basic auth sends credentials with every request (not recommended for production). Session auth uses cookies and is great for browser-based API usage.

Token Authentication

Token auth assigns a unique key to every user. The user sends this key in the header: Authorization: Token 9944b09....

JWT Authentication (Recommended)

In the video, we strongly recommend JWT (JSON Web Tokens) using the simplejwt library. It is stateless and secure.

pip install djangorestframework-simplejwt

Add it to your urls to get the token:

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'),
]

How to Write Your Permission Class

Sometimes the built-in permissions aren’t enough. You can write custom ones. For example, a permission that only allows the author of a post to edit it:

from rest_framework import permissions

class IsAuthorOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.author == request.user

API Documentation with Swagger

Finally, an API is only as good as its documentation. We use drf-yasg or drf-spectacular to generate interactive Swagger UI documentation automatically.

This allows frontend developers to test your endpoints directly in the browser without writing a single line of code.

Documentation significantly contributes to the success and adoption of your API. It provides clarity and facilitates smooth integration.

Conclusion

We have covered a massive amount of ground here! From setting up Django to building a full CRUD system and securing it with JWT. Remember, the best way to learn is by doing.

If you got stuck at any point, please refer to the full 7-hour video tutorial where we code this entire project step-by-step. Happy coding!

Watch The Video

Watch on YouTube

How did this article make you feel?

Share This Post

About admin

Founder and Lead Developer at Halogenius Ideas, bridging the gap between professional web design and accessible tech education. With years of experience in full-stack development and a passion for teaching, I lead a team dedicated to building stunning digital experiences while empowering the next generation of developers through comprehensive tutorials and courses. When I'm not coding or creating content, you'll find me exploring new technologies and mentoring aspiring developers.

Leave a Reply

Your email address will not be published. Required fields are marked *

three + 4 =
Powered by MathCaptcha