Track B · Tutorial 1

Python Backend with Django & FastAPI

Chapter 25 · Backend Specialization
~3 hours Intermediate Django · FastAPI · ORM · Serializers

Overview

Python offers two excellent backend frameworks: Django (batteries‑included) and FastAPI (modern, async, OpenAPI). This tutorial covers both, helping you choose the right tool for the job. You'll build models, serializers, views, and migrations.

Why this matters: Python is one of the most popular backend languages. Knowing both Django and FastAPI makes you versatile and ready for different types of projects.

1. Django REST Framework

Setup

pip install django djangorestframework django-admin startproject myapi . python manage.py startapp products

Model

# products/models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name

Serializer

# products/serializers.py from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'name', 'price', 'created_at']

ViewSet

# products/views.py from rest_framework import viewsets from .models import Product from .serializers import ProductSerializer class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer
# myapi/urls.py from rest_framework.routers import DefaultRouter from products.views import ProductViewSet router = DefaultRouter() router.register('products', ProductViewSet) urlpatterns = router.urls

2. FastAPI

Setup

pip install fastapi uvicorn

App with SQLAlchemy

from fastapi import FastAPI, Depends from sqlalchemy import create_engine, Column, Integer, String, Float from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, Session from pydantic import BaseModel app = FastAPI() Base = declarative_base() class Product(Base): __tablename__ = 'products' id = Column(Integer, primary_key=True) name = Column(String) price = Column(Float) class ProductSchema(BaseModel): name: str price: float # Dependency: get_db()

Endpoints

@app.post('/products') def create_product(product: ProductSchema, db: Session = Depends(get_db)): db_product = Product(name=product.name, price=product.price) db.add(db_product) db.commit() db.refresh(db_product) return db_product @app.get('/products') def get_products(db: Session = Depends(get_db)): return db.query(Product).all()
Async support: FastAPI supports async endpoints. Use async def for database calls with async ORMs like SQLAlchemy async.

3. ORM & Migrations

Django Migrations

python manage.py makemigrations python manage.py migrate

FastAPI (Alembic)

pip install alembic alembic init -t async alembic # Edit alembic/env.py for async support alembic revision --autogenerate -m "create products table" alembic upgrade head

4. Serializers & Schemas

Serializers (Django) and Pydantic schemas (FastAPI) validate and transform data.

FastAPI Pydantic Example

from pydantic import BaseModel, Field from datetime import datetime class ProductCreate(BaseModel): name: str = Field(..., min_length=2, max_length=100) price: float = Field(..., gt=0) class ProductResponse(ProductCreate): id: int created_at: datetime

Quiz

Question 1

Which Django component defines the data structure?

  • View
  • Model
  • Serializer
  • URL
Show answer
B. Model.

Question 2

Which FastAPI library is used for data validation?

  • SQLAlchemy
  • Pydantic
  • Django ORM
  • Marshmallow
Show answer
B. Pydantic.

Question 3

What command creates migrations in Django?

  • python manage.py migrate
  • python manage.py makemigrations
  • python manage.py create
  • python manage.py db
Show answer
B. python manage.py makemigrations.

Exercises

Exercise 1

Create a Django model for a Category with name and description fields.

Sample answer
class Category(models.Model): name = models.CharField(max_length=50) description = models.TextField(blank=True) def __str__(self): return self.name

Exercise 2

Write a FastAPI endpoint that returns a list of products with a status field (success/error).

Sample answer
@app.get('/products', response_model=List[ProductResponse]) async def get_products(db: Session = Depends(get_db)): products = db.query(Product).all() return products

Homework

Homework 1

Implement a complete CRUD API for Order in Django REST Framework with fields: id, product_id, quantity, created_at.

Sample outline
  • Model: Order (product_id, quantity, created_at)
  • Serializer: OrderSerializer
  • ViewSet: OrderViewSet with all CRUD operations
  • URL: router.register('orders', OrderViewSet)

Mini‑Project

Student Management API (FastAPI)

Build a Student Management API with FastAPI and SQLAlchemy:

  • Student: id, name, email, age, grade
  • CRUD endpoints: GET /students, GET /students/{id}, POST, PUT, DELETE
  • Use Pydantic schemas for validation
  • Add a filter endpoint: GET /students?grade=A
Sample implementation outline
  • Model: Student (id, name, email, age, grade)
  • Schemas: StudentCreate, StudentUpdate, StudentResponse
  • Endpoints: async def create_student, get_students, get_student, update_student, delete_student
  • Filter: add query parameter grade: Optional[str] = None

Tutorial Summary

You explored Python's two leading backend frameworks: Django (full‑featured) and FastAPI (modern, async). You built models, migrations, serializers/schemas, and endpoints. You now understand the strengths of each framework and when to choose one over the other.

Key takeaway: Django is ideal for monolithic applications with built‑in admin and ORM. FastAPI is perfect for microservices and async‑heavy workloads with automatic OpenAPI documentation.