Thursday, 20 November 2025

How to Run these Modules Easily

Run the FastAPI 12-Module Course — Step by Step

FastAPI 12-Module Course — How to run Modules 1 → 12 (step-by-step)

This guide assumes you're running locally on a machine with Python 3.10+ and a terminal. Commands include both Linux/macOS and Windows where relevant.

Module 1 — Setup & Hello World

  1. Create a project folder and virtual environment.
# Linux / macOS python3 -m venv .venv source .venv/bin/activate # Windows (PowerShell) python -m venv .venv .venv\Scripts\Activate.ps1
  1. Install FastAPI and Uvicorn.
pip install fastapi uvicorn
  1. Create main.py with the Hello World app.
from fastapi import FastAPI app = FastAPI() @app.get("/") async def read_root(): return {"message": "Hello, FastAPI!"}
  1. Run the server and open the docs.
uvicorn main:app --reload # Open: http://127.0.0.1:8000/docs (Swagger UI) or http://127.0.0.1:8000
Expected: Visiting / returns {"message":"Hello, FastAPI!"}. Swagger UI is auto-generated at /docs.

Module 2 — Path & Query Parameters

  1. In the same project, add endpoints demonstrating path & query params.
from fastapi import FastAPI from typing import Optional app = FastAPI() @app.get("/items/{item_id}") async def read_item(item_id: int): return {"item_id": item_id} @app.get("/search") async def search(q: Optional[str] = None, limit: int = 10): return {"q": q, "limit": limit}
  1. Run server: uvicorn main:app --reload. Test with browser or curl.
# path param curl http://127.0.0.1:8000/items/42 # query param curl "http://127.0.0.1:8000/search?q=fastapi&limit=5"

Module 3 — Request Bodies & Pydantic Models

  1. Create module3.py and define Pydantic models for incoming JSON.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float description: str | None = None @app.post("/items/") async def create_item(item: Item): return {"item": item}
  1. Test using Swagger UI or curl.
curl -X POST "http://127.0.0.1:8000/items/" -H "Content-Type: application/json" -d '{"name":"Book","price":19.99}'
FastAPI validates JSON automatically. If a required field is missing or wrong type, you'll get a structured error response.

Module 4 — Response Models & Output Validation

  1. Use response_model to shape the API output and hide extra fields.
from fastapi import FastAPI from pydantic import BaseModel class ItemOut(BaseModel): name: str price: float app = FastAPI() @app.get("/item", response_model=ItemOut) def get_item(): return {"name": "Laptop", "price": 1200, "secret": "hidden"}
"secret" will be removed from the response thanks to response_model.

Module 5 — CRUD Operations & In-Memory DB

  1. Create an in-memory CRUD app (dictionary-based) — good for quick testing.
from fastapi import FastAPI, HTTPException from pydantic import BaseModel from uuid import uuid4 app = FastAPI() class Item(BaseModel): name: str price: float db = {} @app.post("/items") async def create_item(item: Item): item_id = str(uuid4()) db[item_id] = item return {"id": item_id} @app.get("/items") async def list_items(): return db
Test create → list → delete using curl or Swagger UI.

Module 6 — Dependency Injection

  1. Learn Depends for shared logic (auth, DB sessions).
from fastapi import FastAPI, Depends, HTTPException app = FastAPI() def get_token(): # stub - replace with real logic return "demo-token" @app.get("/secure") def secure_route(token: str = Depends(get_token)): if token != "demo-token": raise HTTPException(status_code=401) return {"status": "ok"}
Use DI to centralize authentication checks, DB session creation, etc.

Module 7 — JWT Authentication (Login & Protect Routes)

  1. Install required packages for JWT and password hashing:
pip install python-jose passlib[bcrypt]
  1. Create token utilities and a login route.
# jwt_utils.py from datetime import datetime, timedelta from jose import jwt SECRET_KEY = "change-me" ALGO = "HS256" EXP_MINUTES = 60 def create_access_token(data: dict): to_encode = data.copy() to_encode.update({"exp": datetime.utcnow() + timedelta(minutes=EXP_MINUTES)}) return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGO)
Add login route that returns the token, then use OAuth2PasswordBearer or a custom dependency to validate on protected routes.

Module 8 — Background Tasks

  1. Use FastAPI's BackgroundTasks for non-critical, post-response work (sending emails, logs).
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def write_log(message: str): with open("log.txt","a") as f: f.write(message + "\\n") @app.post("/notify") async def notify(email: str, background_tasks: BackgroundTasks): background_tasks.add_task(write_log, f"Notified {email}") return {"status": "scheduled"}
Background tasks run after the response is sent.

Module 9 — File Uploads & Streaming Responses

  1. Use UploadFile to receive files efficiently.
from fastapi import FastAPI, UploadFile, File app = FastAPI() @app.post("/upload") async def upload_file(file: UploadFile = File(...)): content = await file.read() return {"filename": file.filename, "size": len(content)}
  1. Stream large files with StreamingResponse.
from fastapi import FastAPI from fastapi.responses import StreamingResponse app = FastAPI() @app.get("/stream") def stream_file(): def gen(): for i in range(5): yield f"line {i}\\n" return StreamingResponse(gen(), media_type="text/plain")

Module 10 — Async Database (SQLModel) & CRUD

  1. Install SQLModel and async driver:
pip install sqlmodel aiosqlite
  1. Create models, async engine, and routes (example skeleton below).
# models.py from sqlmodel import SQLModel, Field from typing import Optional class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str price: float
Run server and use /docs to create/list/update entries through the auto-generated UI.

Module 11 — WebSockets (Real-Time Chat)

  1. Create a connection manager and WebSocket route.
from fastapi import FastAPI, WebSocket, WebSocketDisconnect app = FastAPI() clients = [] @app.websocket("/ws") async def websocket_endpoint(ws: WebSocket): await ws.accept() clients.append(ws) try: while True: data = await ws.receive_text() for c in clients: await c.send_text(f"User said: {data}") except WebSocketDisconnect: clients.remove(ws)
Open a simple HTML client (2 browser tabs) to test live chat.

Module 12 — Deployment (Docker, Gunicorn, Render, Nginx)

  1. Create a production start script using Gunicorn + Uvicorn workers.
# start.sh exec gunicorn app.main:app \ --workers 4 \ --worker-class uvicorn.workers.UvicornWorker \ --bind 0.0.0.0:8000
  1. Dockerfile example:
FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . CMD ["./start.sh"]
Push to GitHub and connect to Render/Railway or build & push to Docker Hub for cloud deployment.

No comments:

Post a Comment

Diagnosis for running all Scripts

 Great — here is the complete ready-to-run folder structure for all 12 FastAPI modules , including: ✅ __init__.py (so Python treats folder...