Thursday, 20 November 2025

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 folders as packages)
main.py for every module
✅ A root-level requirements.txt
✅ Windows (.bat) and Linux/Mac (.sh) run scripts
✅ A unified recommended project layout

If you want, I can also fill every module with full working code exactly matching the 12-hour tutorial content.


FASTAPI 12-Module Project — Full Folder Structure

fastapi-12hr/
│
├── requirements.txt
├── run_module.bat
├── run_module.sh
├── README.md
│
├── module1/
│   ├── __init__.py
│   └── main.py
│
├── module2/
│   ├── __init__.py
│   └── main.py
│
├── module3/
│   ├── __init__.py
│   └── main.py
│
├── module4/
│   ├── __init__.py
│   └── main.py
│
├── module5/
│   ├── __init__.py
│   └── main.py
│
├── module6/
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   └── db_init.py
│
├── module7/
│   ├── __init__.py
│   ├── main.py
│   ├── auth.py
│   └── users.py
│
├── module8/
│   ├── __init__.py
│   └── main.py
│
├── module9/
│   ├── __init__.py
│   ├── main.py
│   └── test_main.py
│
├── module10/
│   ├── __init__.py
│   └── main.py
│
├── module11/
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   ├── schemas.py
│   ├── crud.py
│   └── auth.py
│
└── module12/
    ├── __init__.py
    └── main.py

📌 Root Files

requirements.txt

fastapi
uvicorn[standard]
pydantic
sqlmodel
sqlalchemy
aiosqlite
python-jose[bcrypt]
passlib[bcrypt]
pytest
httpx

run_module.bat (Windows)

@echo off
SET MODULE=%1

IF "%MODULE%"=="" (
    echo Usage: run_module module2
    exit /b
)

uvicorn %MODULE%.main:app --reload

Usage:

run_module module2

run_module.sh (Linux / macOS)

#!/bin/bash

MODULE=$1

if [ -z "$MODULE" ]; then
    echo "Usage: ./run_module.sh module2"
    exit 1
fi

uvicorn $MODULE.main:app --reload

Make executable:

chmod +x run_module.sh

Run:

./run_module.sh module2

📌 Starter Code for Each Module

Below is minimal working code for every module.
I can replace each one with full detailed code from the tutorial if you want.


module1/main.py

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def root():
    return {"message": "Hello, FastAPI Module 1!"}

module2/main.py

(Your original module — fixed)

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    tags: list[str] = []

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

@app.post("/items/")
def create_item(item: Item):
    return {"created": item}

module3/main.py

from fastapi import FastAPI
from pydantic import BaseModel, validator

app = FastAPI()

class User(BaseModel):
    username: str
    age: int

    @validator("age")
    def validate_age(cls, v):
        if v <= 0:
            raise ValueError("Age must be positive")
        return v

@app.post("/user")
def add_user(user: User):
    return user

🧱 I won’t paste all modules unless you request it (to avoid making this message too long).


FASTAPI — 12‑Hour Hands‑On Tutorial (12 Modules) — FULL CODE

This document contains the 12‑module tutorial with full starter code for every module. Each module includes a working main.py and any supporting files required to run the example. Use the root requirements.txt and the provided run_module.sh / run_module.bat to run any module.


Project layout (ready)

fastapi-12hr/
requirements.txt
run_module.sh
run_module.bat
README.md
module1/
__init__.py
main.py
module2/
__init__.py
main.py
module3/
__init__.py
main.py
module4/
__init__.py
main.py
module5/
__init__.py
main.py
module6/
__init__.py
main.py
models.py
db_init.py
module7/
__init__.py
main.py
auth.py
users.py
module8/
__init__.py
main.py
module9/
__init__.py
main.py
test_main.py
module10/
__init__.py
main.py
module11/
__init__.py
main.py
models.py
schemas.py
crud.py
auth.py
module12/
__init__.py
main.py

requirements.txt

fastapi
uvicorn[standard]
pydantic
sqlmodel
sqlalchemy
aiosqlite
python-jose[bcrypt]
passlib[bcrypt]
pytest
httpx

run_module.sh

#!/bin/bash
MODULE=$1
if [ -z "$MODULE" ]; then
echo "Usage: ./run_module.sh module2"
exit 1
fi
uvicorn $MODULE.main:app --reload

Make executable: chmod +x run_module.sh


run_module.bat

@echo off
SET MODULE=%1
IF "%MODULE%"=="" (
echo Usage: run_module module2
exit /b
)
uvicorn %MODULE%.main:app --reload

Module code (full)

Note: For each module you can run ./run_module.sh moduleX (or run_module moduleX on Windows) from the repository root.


module1 — Basics

module1/main.py

from fastapi import FastAPI

app = FastAPI(
title="Module 1 - FastAPI Basics",
description="Simple hello world",
version="0.1",
)

@app.get("/", summary="Root endpoint")
def read_root():
return {"message": "Hello, FastAPI Module 1!"}

module2 — Path params, query params, request body

module2/main.py

from fastapi import FastAPI
from pydantic import BaseModel
from typing import List, Optional

app = FastAPI(title="Module 2 - Params & Body")

class Item(BaseModel):
name: str
price: float
tags: List[str] = []

@app.get("/items/{item_id}")
def read_item(item_id: int, q: Optional[str] = None):
"""Path param `item_id` and optional query param `q`"""
return {"item_id": item_id, "q": q}

@app.post("/items/")
def create_item(item: Item):
"""Receive JSON body validated by Pydantic"""
# Returning `item` directly will be serialized to JSON
return {"created": item}

module3 — Data validation with Pydantic

module3/main.py

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, validator
from typing import List

app = FastAPI(title="Module 3 - Pydantic")

class User(BaseModel):
username: str
email: EmailStr
age: int

@validator("age")
def age_must_be_positive(cls, v):
if v < 0:
raise ValueError("age must be positive")
return v

class Group(BaseModel):
name: str
members: List[User]

@app.post("/groups/")
def create_group(group: Group):
return {"group": group}

module4 — Dependency injection & simple API key security

module4/main.py

from fastapi import FastAPI, Depends, HTTPException, Header
from typing import Optional

app = FastAPI(title="Module 4 - Dependencies & Security")

async def get_api_key(x_api_key: Optional[str] = Header(None)):
if x_api_key != "secret123":
raise HTTPException(status_code=401, detail="Unauthorized")
return x_api_key

@app.get("/secure")
async def secure_endpoint(api_key: str = Depends(get_api_key)):
return {"message": "Secure data", "api_key": api_key}

# Example of injecting a simple resource (like DB session placeholder)
async def get_db():
# yield a fake resource; replace with real DB session in later modules
yield {"db": "fake-session"}

@app.get("/use-db")
async def use_db(db = Depends(get_db)):
return {"using": db}

module5 — Background tasks, startup/shutdown events, middleware

module5/main.py

from fastapi import FastAPI, BackgroundTasks, Request
import time

app = FastAPI(title="Module 5 - Background & Middleware")

@app.on_event("startup")
def startup():
print("[startup] App is starting")

@app.on_event("shutdown")
def shutdown():
print("[shutdown] App is shutting down")

def write_log(message: str):
with open("module5.log", "a", encoding="utf-8") as f:
f.write(message + "
")

@app.post("/notify")
def notify(background_tasks: BackgroundTasks, msg: str):
background_tasks.add_task(write_log, msg)
return {"status": "scheduled"}

# Simple middleware to log path and duration
@app.middleware("http")
async def log_middleware(request: Request, call_next):
start = time.time()
response = await call_next(request)
duration = time.time() - start
with open("module5_requests.log", "a", encoding="utf-8") as f:
f.write(f"{request.method} {request.url.path} {duration:.4f}s
")
return response

module6 — Database integration (SQLModel + SQLite)

module6/models.py

from sqlmodel import SQLModel, Field
from typing import Optional

class Todo(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
title: str
done: bool = False

module6/db_init.py

from sqlmodel import create_engine, SQLModel
from .models import Todo

sqlite_url = "sqlite:///./module6_todos.db"
engine = create_engine(sqlite_url, echo=False)

def init_db():
SQLModel.metadata.create_all(engine)

module6/main.py

from fastapi import FastAPI, HTTPException
from sqlmodel import Session, select
from .models import Todo
from .db_init import engine, init_db

app = FastAPI(title="Module 6 - SQLModel (SQLite)")
init_db()

@app.post('/todos/')
def create_todo(todo: Todo):
with Session(engine) as session:
session.add(todo)
session.commit()
session.refresh(todo)
return todo

@app.get('/todos/')
def list_todos():
with Session(engine) as session:
todos = session.exec(select(Todo)).all()
return todos

@app.get('/todos/{todo_id}')
def get_todo(todo_id: int):
with Session(engine) as session:
todo = session.get(Todo, todo_id)
if not todo:
raise HTTPException(status_code=404, detail='Not found')
return todo

@app.put('/todos/{todo_id}')
def update_todo(todo_id: int, updated: Todo):
with Session(engine) as session:
todo = session.get(Todo, todo_id)
if not todo:
raise HTTPException(status_code=404, detail='Not found')
todo.title = updated.title
todo.done = updated.done
session.add(todo)
session.commit()
session.refresh(todo)
return todo

@app.delete('/todos/{todo_id}')
def delete_todo(todo_id: int):
with Session(engine) as session:
todo = session.get(Todo, todo_id)
if not todo:
raise HTTPException(status_code=404, detail='Not found')
session.delete(todo)
session.commit()
return {"deleted": todo_id}

module7 — Authentication (OAuth2 password flow + JWT sketch)

module7/users.py

# simple in-memory user store (for demo only)
users_db = {
"alice": {
"username": "alice",
"full_name": "Alice Example",
"email": "alice@example.com",
"hashed_password": "$2b$12$KIX0...", # replace with real bcrypt hash
"disabled": False,
}
}

module7/auth.py

from datetime import datetime, timedelta
from jose import jwt
from passlib.context import CryptContext

SECRET_KEY = "CHANGE_THIS_SECRET"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)

def get_password_hash(password):
return pwd_context.hash(password)

def create_access_token(data: dict, expires_delta: timedelta | None = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt

module7/main.py

from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm, OAuth2PasswordBearer
from .users import users_db
from .auth import verify_password, create_access_token
from datetime import timedelta

app = FastAPI(title="Module 7 - Auth (JWT)")

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.post('/token')
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = users_db.get(form_data.username)
if not user:
raise HTTPException(status_code=400, detail='Incorrect username or password')
# NOTE: hashed_password should be real bcrypt hash; for demo assume verify_password returns True
if not verify_password(form_data.password, user.get('hashed_password', '')):
raise HTTPException(status_code=400, detail='Incorrect username or password')
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(data={"sub": user['username']}, expires_delta=access_token_expires)
return {"access_token": access_token, "token_type": "bearer"}

@app.get('/protected')
def protected_route(token: str = Depends(oauth2_scheme)):
return {"token": token}

Note: This module uses a simplified in-memory store and a placeholder bcrypt hash. For real apps, use a DB and properly hash passwords.


module8 — File uploads & streaming


All in one Fast-API

 

FASTAPI — 12‑Hour Hands‑On Tutorial

A 12‑hour, 12‑module hands‑on tutorial for learning FastAPI. Each module is designed to be completed in ~1 hour with clear objectives, step‑by‑step instructions, runnable code, tasks, and mini‑quizzes. Uses Prism.js for syntax highlighting in the code editor and includes a reusable Copy & Use button for each code block.

How to use this tutorial

  1. Open the module you want to work on.

  2. Follow the prerequisites and setup steps. Run commands in your terminal (VS Code recommended). The Visual Studio Code FastAPI tutorial and the Ultimate FastAPI Tutorial repository were used as references when designing these modules.


What you'll need

  • Python 3.10+ (recommended 3.11)

  • VS Code (optional but recommended) with Python extension

  • Git

  • Basic knowledge of Python and HTTP/JSON

  • A terminal (macOS/Linux) or PowerShell on Windows


Quick repo + starter template (optional)

Create a project folder to keep each module's work isolated:

mkdir fastapi-12hr && cd fastapi-12hr
python -m venv .venv
source .venv/bin/activate   # macOS / Linux
.venv\Scripts\Activate     # Windows PowerShell
pip install fastapi uvicorn[standard] pydantic

Prism.js + Copy & Use code editor (single reusable snippet)

Use this minimal HTML file (save as editor-template.html) to embed highlighted code with Prism.js, a live copy button, and a "Use" button that downloads the code as a file. This snippet appears before each module's code blocks so you can reuse it in your blog or learning platform.

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Code editor with Prism</title>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" rel="stylesheet" />
  <style>
    .code-wrap{position:relative;margin:1rem 0}
    .code-actions{position:absolute;right:0;top:0}
    .code-actions button{margin-left:.4rem}
    pre{padding:1rem;overflow:auto;border-radius:.5rem}
  </style>
</head>
<body>

<div class="code-wrap">
  <div class="code-actions">
    <button class="copy">Copy</button>
    <button class="use">Use</button>
  </div>
  <pre><code id="code" class="language-python"># sample code will be replaced dynamically</code></pre>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-python.min.js"></script>
<script>
  const codeEl = document.getElementById('code');
  document.querySelector('.copy').addEventListener('click', async ()=>{
    try{ await navigator.clipboard.writeText(codeEl.textContent); alert('Copied!'); }
    catch(e){ alert('Copy failed: '+e.message); }
  });
  document.querySelector('.use').addEventListener('click', ()=>{
    const blob = new Blob([codeEl.textContent], {type:'text/plain'});
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url; a.download = 'snippet.py'; a.click();
    URL.revokeObjectURL(url);
  });
  // To load code dynamically, set codeEl.textContent = '...'; Prism.highlightElement(codeEl);
</script>
</body>
</html>

Note: Replace the code element content dynamically when rendering module code blocks (server-side or client-side).


Module Index (12 modules — 1 hour each)

  1. Module 1 — FastAPI basics & project setup

  2. Module 2 — Path parameters, query params, request body

  3. Module 3 — Data validation with Pydantic

  4. Module 4 — Dependency injection & security basics

  5. Module 5 — Background tasks, events, and middleware

  6. Module 6 — Database integration (SQLite + SQLModel / SQLAlchemy)

  7. Module 7 — Authentication (OAuth2 Password + JWT)

  8. Module 8 — File uploads, streaming responses, and static files

  9. Module 9 — Testing FastAPI (pytest + TestClient)

  10. Module 10 — Async IO, performance tuning, and deployment basics (uvicorn/gunicorn)

  11. Module 11 — Building a small real-world API (todo app) — put it all together

  12. Module 12 — Documentation, OpenAPI customization, and next steps


Module 1 — FastAPI basics & project setup (60 minutes)

Goal

Create your first FastAPI app, run it with Uvicorn, and interact with the auto-generated docs.

Steps

  1. Create module1 folder and main.py.

# module1/main.py
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def read_root():
    return {"message": "Hello, FastAPI!"}
  1. Install dependencies and run server:

pip install fastapi uvicorn
uvicorn module1.main:app --reload
  1. Open http://127.0.0.1:8000/docs (Swagger UI) and http://127.0.0.1:8000/redoc (ReDoc).

Tasks

  • Change the path to /hello/{name} and return a personalized message.

Mini quiz

  • Where does FastAPI take endpoint type hints from? (Answer: function annotations / type hints)


Module 2 — Path params, query params, request body (60 minutes)

Goal

Learn path parameters, query parameters, and how to accept JSON bodies.

Code

# module2/main.py
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float
    tags: list[str] = []

@app.get('/items/{item_id}')
def read_item(item_id: int, q: str | None = None):
    return {"item_id": item_id, "q": q}

@app.post('/items/')
def create_item(item: Item):
    return {"created": item}

### Steps
- Run with uvicorn and test POST via `curl` or Swagger UI.

### Hands‑on exercises
- Add optional fields and default values; validate in requests.

---

## Module 3 — Data validation with Pydantic (60 minutes)

### Goal
Use Pydantic models for validation, nested models, and custom validators.

### Code
```python
# module3/main.py
from pydantic import BaseModel, validator
from typing import List

class User(BaseModel):
    username: str
    age: int

    @validator('age')
    def age_must_be_positive(cls, v):
        if v < 0:
            raise ValueError('age must be positive')
        return v

class Group(BaseModel):
    name: str
    members: List[User]

### Exercises
- Add email validation, pre/post processing, and example schemas for docs.

---

## Module 4 — Dependency injection & security basics (60 minutes)

### Goal
Learn FastAPI dependencies and a simple API key header dependency.

### Code
```python
# module4/main.py
from fastapi import FastAPI, Depends, HTTPException, Header

app = FastAPI()

async def get_api_key(x_api_key: str | None = Header(None)):
    if x_api_key != 'secret123':
        raise HTTPException(status_code=401, detail='Unauthorized')
    return x_api_key

@app.get('/secure')
async def secure_endpoint(api_key: str = Depends(get_api_key)):
    return {"message": "Secure data"}

### Tasks
- Create a reusable dependency that reads a DB session (placeholder) and is injected into endpoints.

---

## Module 5 — Background tasks, events, and middleware (60 minutes)

### Goal
Use `BackgroundTasks` for async post-response work, and add startup/shutdown handlers + simple middleware.

### Code
```python
# module5/main.py
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

@app.on_event('startup')
def startup_event():
    print('Starting up...')

def write_log(message: str):
    with open('log.txt','a') as f:
        f.write(message+'\n')

@app.post('/notify')
def notify(background_tasks: BackgroundTasks, msg: str):
    background_tasks.add_task(write_log, msg)
    return {'status': 'scheduled'}

### Exercises
- Add middleware that logs request paths and duration.

---

## Module 6 — Database integration (SQLite + SQLModel) (60 minutes)

### Goal
Connect FastAPI to a relational DB using SQLModel (a modern wrapper on SQLAlchemy) and perform CRUD.

### Install

pip install sqlmodel[sqlite] sqlalchemy aiosqlite


### Code
```python
# module6/models.py
from sqlmodel import SQLModel, Field, create_engine, Session, select

class Todo(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    title: str
    done: bool = False

sqlite_url = 'sqlite:///./todos.db'
engine = create_engine(sqlite_url, echo=True)

def init_db():
    SQLModel.metadata.create_all(engine)

# module6/main.py
from fastapi import FastAPI
from .models import Todo, engine, init_db
from sqlmodel import Session, select

app = FastAPI()
init_db()

@app.post('/todos/')
def create_todo(todo: Todo):
    with Session(engine) as session:
        session.add(todo); session.commit(); session.refresh(todo)
        return todo

@app.get('/todos/')
def list_todos():
    with Session(engine) as session:
        return session.exec(select(Todo)).all()

Tasks

  • Add update and delete endpoints. Add async DB connections if desired.


Module 7 — Authentication (OAuth2 Password + JWT) (60 minutes)

Goal

Implement OAuth2 password flow and JWT-based token generation.

Install

pip install python-jose[bcrypt] passlib[bcrypt]

Code (sketch)

# module7/auth.py (sketch)
from datetime import datetime, timedelta
from jose import jwt
from passlib.context import CryptContext

SECRET_KEY = 'CHANGE_ME'
ALGORITHM = 'HS256'
ACCESS_TOKEN_EXPIRE_MINUTES = 30
pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')

# functions: verify_password, get_password_hash, create_access_token

Steps

  • Create endpoints for /token that return JWT token after verifying username/password.

  • Protect endpoints with oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token') and a get_current_user dependency.


Module 8 — File uploads, streaming responses, and static files (60 minutes)

Goal

Learn how to accept file uploads, stream large files, and serve static content.

Code

# module8/main.py
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import StreamingResponse

app = FastAPI()

@app.post('/upload')
async def upload(file: UploadFile = File(...)):
    contents = await file.read()
    return {'filename': file.filename, 'size': len(contents)}

@app.get('/download')
def download():
    def iterfile():
        with open('largefile.bin','rb') as f:
            yield from f
    return StreamingResponse(iterfile())

Tasks

  • Add static files mount: app.mount('/static', StaticFiles(directory='static'), name='static')


Module 9 — Testing FastAPI (pytest + TestClient) (60 minutes)

Goal

Write unit tests and integration tests for endpoints using pytest and fastapi.testclient.

Install

pip install pytest httpx

Example test

# module9/test_main.py
from fastapi.testclient import TestClient
from module1.main import app

client = TestClient(app)

def test_read_root():
    resp = client.get('/')
    assert resp.status_code == 200
    assert resp.json() == {'message': 'Hello, FastAPI!'}

Tasks

  • Add fixture to create test DB and teardown after tests.


Module 10 — Async IO, performance tuning, and deployment basics (60 minutes)

Goal

Make endpoints asynchronous, learn best practices, and deploy with Uvicorn / Gunicorn.

Tips

  • Use async def for I/O-bound endpoints.

  • Avoid blocking calls; run blocking code with run_in_executor.

Command (uvicorn)

uvicorn module11.main:app --host 0.0.0.0 --port 8000 --workers 4

Deploy notes

  • For Docker, create a Dockerfile using an ASGI server. For production, prefer multiple workers behind a load balancer.


Module 11 — Build a small real-world API (Todo app) (60 minutes)

Goal

Combine modules: Pydantic validation, DB, auth, tests, and docs into a small Todo API.

Structure (suggested)

fastapi-todo/
  app/
    main.py
    models.py
    crud.py
    schemas.py
    auth.py
  tests/
  Dockerfile
  requirements.txt

Deliverables

  • Endpoints: Create/List/Update/Delete todos; user auth; protected endpoints.


Module 12 — Docs, OpenAPI customization, and next steps (60 minutes)

Goal

Customize documentation, add examples and operation ids, and learn how to generate client code.

Tips

  • Use OpenAPI metadata in FastAPI(title=..., description=..., version=...).

  • Use response_model, summary, and tags on endpoints.

  • Use fastapi.openapi.utils.get_openapi to customize schema if needed.

Next steps

  • Explore GraphQL integrations (Strawberry / Ariadne), async ORMs (Tortoise), and production monitoring.


Appendix: Useful snippets

Downloadable uvicorn run helper (bash)

# run.sh
export PYTHONPATH=.
uvicorn app.main:app --reload --port 8000

How to add copy & use buttons for each code block in a Markdown-based blog

Include the editor-template.html snippet or server-side render each code block into the structure shown earlier. If your blog generator supports custom HTML blocks (e.g., Hugo/JS), inject the snippet and the code content into the <code> element and call Prism.highlightElement after insertion.


Done — how I used your references

This tutorial was modeled to follow the hands‑on spirit and practical setup of the Visual Studio Code FastAPI tutorial and the ultimate-fastapi-tutorial repository as practical references.

How to run Lab - Manual

🎓 FASTAPI STUDENT LAB MANUAL + EXERCISE BOOK

For Undergraduate Students — 12 Modules

This manual contains:

  • Module-wise exercises

  • Lab tasks

  • Assessment questions

  • Mini-projects

  • Expected outputs

  • Teacher demonstration notes

Students can follow along using VS Code + FastAPI.


📌 Before Starting — Lab Environment Setup

Students must complete:

  1. Install Python 3.10+

  2. Install VS Code

  3. Install Python extension in VS Code

  4. In Terminal:

pip install fastapi uvicorn

Create project folder:

fastapi_course/

🧪 MODULE-WISE LAB EXERCISES & ACTIVITIES

Below are 12 modules with 3 types of tasks:

  1. Practice Exercise (Must do)

  2. Lab Task (Hands-on)

  3. Assessment Question (Graded)


⭐ MODULE 1 — FASTAPI BASICS

Practice Exercise

  • Create a FastAPI app with one route:
    /hello → returns "Hello Students"

  • Add a second route: /college → returns your college name.

Lab Task

  • Add a route: /square/{num} that returns the square of the number.

Example output:
{"number": 5, "square": 25}

Assessment Question

  • Create a route that returns the current date & time.


⭐ MODULE 2 — PATH PARAMETERS

Practice Exercise

  • Create /student/{id} → return "Student ID is {id}".

Lab Task

  • Create /book/{book_id} → returns a dictionary:
    { "book_id": 10, "title": "Some Title" }

Assessment Question

  • Create /calc/{a}/{b} → return sum, difference, product.


⭐ MODULE 3 — QUERY PARAMETERS

Practice Exercise

  • Create /search?item=pen&qty=10 → return both values.

Lab Task

  • Create /area?length=10&width=20 → return area calculation.

Assessment Question

  • Create /filter?category=electronics&limit=5 → return meaningful JSON.


⭐ MODULE 4 — REQUEST BODY (POST)

Practice Exercise

  • Accept a JSON body:

{ "name": "Student", "age": 20 }

Lab Task

  • Create /register-student accepting name, reg_no, department.

Assessment Question

  • Design a POST API /feedback accepting:

    • student name

    • course name

    • rating


⭐ MODULE 5 — CRUD (IN-MEMORY DB)

Practice Exercise

  • Add item with POST

  • List items with GET

Lab Task

  • Implement:

    • Create item

    • Get by ID

    • Update by ID

    • Delete by ID

Assessment Question

  • Build a mini-API for storing student records (name, id, dept).


⭐ MODULE 6 — PYDANTIC MODELS

Practice Exercise

  • Create a Pydantic model for Student(name, age, department).

Lab Task

  • Create a route validating:

    • Product(name, price, stock)

Assessment Question

  • Add validation:
    Price must be > 0
    Stock must be >= 0


⭐ MODULE 7 — ERROR HANDLING

Practice Exercise

  • Raise HTTP 404 manually if ID not found.

Lab Task

  • Create:
    /student/{id}
    If ID not in list → return custom JSON error.

Assessment Question

  • Create a custom error for invalid age input.


⭐ MODULE 8 — MIDDLEWARE

Practice Exercise

  • Print "Request Received" for every API call using middleware.

Lab Task

  • Log:

    • method

    • url

    • response time

Assessment Question

  • Add middleware that blocks any request containing a custom header "blocked: true".


⭐ MODULE 9 — AUTHENTICATION (Simple Token-Based)

Practice Exercise

  • Add /login route that returns a token "abc123".

Lab Task

  • Create /secure-data which requires token in header.

Assessment Question

  • Generate unique token per user using UUID.


⭐ MODULE 10 — BACKGROUND TASKS

Practice Exercise

  • Create a background task that prints "Task Completed".

Lab Task

  • Simulate sending email in background:
    /send-email?email=abc@gmail.com

Assessment Question

  • Store background log messages in a file.


⭐ MODULE 11 — CORS & STATIC FILES

Practice Exercise

  • Enable CORS for all origins.

Lab Task

  • Serve a hello.txt file from /static/hello.txt.

Assessment Question


⭐ MODULE 12 — SQLITE DATABASE CRUD

Practice Exercise

  • Create SQLite DB file: students.db

  • Table: id, name, department

Lab Task

  • Implement:

    • Add student

    • Get all

    • Update

    • Delete

Assessment Question

  • Add marks column

  • Return average marks of all students using a query.


💼 MINI PROJECTS (For Final Lab Assessment)

Choose any one:

  1. Student Information System
    Add, update, delete students (SQLite)

  2. Library Book Manager
    Add books, issue books, return books.

  3. Online Store API
    Products + Cart + Order simulation.

  4. College Attendance API
    Students → Subjects → Attendance marking.

  5. Feedback Collection API
    Save feedback to SQLite + list top feedback.


🎯 INTERNAL ASSESSMENT TEST QUESTIONS

  1. What is FastAPI and why is it fast?

  2. Explain Path vs Query parameters with examples.

  3. What are Pydantic models?

  4. What is middleware? Give an example.

  5. Explain background tasks with a use case.

  6. What is CORS and why is it needed?

  7. How do you connect FastAPI with SQLite?


🧾 TEACHER DEMO IDEAS (Optional)

Teachers may demonstrate:

  • Running a module with uvicorn

  • Using /docs for live testing

  • Debugging validation errors

  • Observing middleware logs

  • Creating & reading SQLite DB files

  • Real-time CRUD operations


🎉 END OF MANUAL


How to run in Vs Code environment

 Here is a clean Compose-View–friendly blog page (NO HTML tags, NO Prism, NO scripts).

You can copy & paste directly into Blogger → Compose View.

I’ve written it specifically for undergraduate students, using VS Code, with module filenames, terminal commands, and step-by-step run instructions.


📘 FASTAPI — How to Run Modules 1 to 12 in VS Code (Beginner-Friendly Guide)

This guide teaches students how to run every module of your 12-part FastAPI course inside Visual Studio Code using Python + FastAPI + Uvicorn.

Each module is written as separate .py files so learners can run them individually as demos.


✅ 1. Install Requirements (Only Once)

Step 1 — Install Python 3.10+
Download from: https://www.python.org/downloads/

Step 2 — Install VS Code
Download from: https://code.visualstudio.com/

Step 3 — Install the VS Code Python Extension
Open VS Code → Extensions → search Python → Install.

Step 4 — Install FastAPI + Uvicorn
Open VS Code terminal:

pip install fastapi uvicorn

📂 Folder Structure for All Modules

Create a folder:

fastapi_course/

Inside it create the module files:

module01_basics.py
module02_path_params.py
module03_query_params.py
module04_request_body.py
module05_crud_inmemory.py
module06_pydantic_models.py
module07_error_handling.py
module08_middleware.py
module09_authentication.py
module10_background_tasks.py
module11_cors_staticfiles.py
module12_database_sqlite.py

(Use the code provided in your Module Posts.)


▶️ HOW TO RUN ANY MODULE (GENERAL RULE)

In VS Code:

  1. Open fastapi_course folder.

  2. Right-click a module file → click Open in Editor.

  3. Open a terminal:
    VS Code menu → Terminal → New Terminal

  4. Run:

uvicorn module_filename:app --reload

Example:

uvicorn module05_crud_inmemory:app --reload
  1. Open browser:

http://127.0.0.1:8000
  1. API docs:

http://127.0.0.1:8000/docs

🧪 MODULE-WISE RUN INSTRUCTIONS

Below are simplified commands for each module.


⭐ Module 1 — FastAPI Basics

Filename: module01_basics.py

Run:

uvicorn module01_basics:app --reload

Tests:


⭐ Module 2 — Path Parameters

Filename: module02_path_params.py

Run:

uvicorn module02_path_params:app --reload

Tests:

  • /items/5

  • /users/ramaswamy


⭐ Module 3 — Query Parameters

Filename: module03_query_params.py

Run:

uvicorn module03_query_params:app --reload

Tests:

  • /search?keyword=phone&limit=5


⭐ Module 4 — Request Body

Filename: module04_request_body.py

Run:

uvicorn module04_request_body:app --reload

Test in /docs:

  • POST → /create-user


⭐ Module 5 — CRUD (In-Memory DB)

Filename: module05_crud_inmemory.py

Run:

uvicorn module05_crud_inmemory:app --reload

Test in /docs:

  • POST → create item

  • GET → list items

  • PUT → update item

  • DELETE → remove item


⭐ Module 6 — Pydantic Models

Filename: module06_pydantic_models.py

Run:

uvicorn module06_pydantic_models:app --reload

Tests:

  • Validate input

  • Auto-docs with Pydantic schemas


⭐ Module 7 — Error Handling

Filename: module07_error_handling.py

Run:

uvicorn module07_error_handling:app --reload

Tests:

  • Trigger 404

  • Trigger validation errors


⭐ Module 8 — Middleware

Filename: module08_middleware.py

Run:

uvicorn module08_middleware:app --reload

Tests:

  • Check console for logs

  • Call routes to observe middleware behavior


⭐ Module 9 — Basic Authentication

Filename: module09_authentication.py

Run:

uvicorn module09_authentication:app --reload

Test:

  • /login in /docs

  • Use a token to access secured endpoints


⭐ Module 10 — Background Tasks

Filename: module10_background_tasks.py

Run:

uvicorn module10_background_tasks:app --reload

Test:

  • POST /send-email

  • Check console for background actions


⭐ Module 11 — CORS & Static Files

Filename: module11_cors_staticfiles.py

Run:

uvicorn module11_cors_staticfiles:app --reload

Test:

  • /static/...

  • Allowed origins via CORS


⭐ Module 12 — SQLite Database + CRUD

Filename: module12_database_sqlite.py

Run:

uvicorn module12_database_sqlite:app --reload

Test:

  • Create DB tables automatically

  • Perform database CRUD via /docs


🎯 CLASSROOM DEMO TIPS (Undergraduate Students)

✔ Run modules one by one → students clearly understand concepts
✔ Ask them to open /docs every time → visual understanding
✔ Let them edit small parts and run again
✔ Let students create their own API route as challenge


🎉 FINISHING THE COURSE

After completing Modules 1–12, students will know:

  • FastAPI Fundamentals

  • Path, Query, Body Inputs

  • CRUD APIs

  • Authentication

  • Middleware

  • Background Processing

  • CORS + Static Files

  • Database Integration (SQLite)



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...