Thursday, 20 November 2025

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)



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.

#12 Deployment Complete!


๐ŸŽ‰ Deployment Complete!

At this point, you have:

  • Dockerized FastAPI app
  • Cloud deployment on Render / Railway
  • Nginx reverse proxy
  • Gunicorn + Uvicorn in production
  • Folder structure for real apps

You can now deploy enterprise-grade FastAPI applications.


#11 WebSockets (Real-Time Chat)

FastAPI Module 11 — WebSockets (Real-Time Chat)

Module 11 — WebSockets (Real-Time Chat)

In this module, you’ll learn how to build a real-time chat system using FastAPI’s WebSocket support. We’ll also create a simple frontend chat UI to test instantly.


1️⃣ WebSocket Basics

A WebSocket connection stays open and allows bi-directional messaging, unlike normal HTTP.

from fastapi import FastAPI, WebSocket app = FastAPI() @app.websocket("/ws") async def websocket_demo(ws: WebSocket): await ws.accept() await ws.send_text("Connection established!") while True: msg = await ws.receive_text() await ws.send_text(f"You said: {msg}")

2️⃣ Chat Manager — Handle Multiple Connected Clients

We create a class to store and broadcast messages to all active users.

class ConnectionManager: def __init__(self): self.active: list[WebSocket] = [] async def connect(self, ws: WebSocket): await ws.accept() self.active.append(ws) def disconnect(self, ws: WebSocket): self.active.remove(ws) async def broadcast(self, message: str): for conn in self.active: await conn.send_text(message) manager = ConnectionManager()

3️⃣ Full WebSocket Chat Route

from fastapi import FastAPI, WebSocket, WebSocketDisconnect from manager import manager app = FastAPI() @app.websocket("/chat") async def chat_socket(ws: WebSocket): await manager.connect(ws) await manager.broadcast("๐Ÿ”ต A new user joined the chat") try: while True: msg = await ws.receive_text() await manager.broadcast(f"User: {msg}") except WebSocketDisconnect: manager.disconnect(ws) await manager.broadcast("๐Ÿ”ด A user left the chat")

4️⃣ Frontend Chat UI (HTML + JavaScript)

Save this as chat.html and open in a browser.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>FastAPI Chat</title> <style> body {background:#0e1522; color:white; font-family:Arial; padding:20px;} #chat {border:1px solid #333; padding:10px; height:300px; overflow-y:auto; background:#111;} input {width:80%; padding:8px;} button {padding:8px 12px; cursor:pointer;} </style> </head> <body> <h2>FastAPI WebSocket Chat</h2> <div id="chat"></div> <input id="msg" placeholder="Type message..." /> <button onclick="sendMsg()">Send</button> <script> let socket = new WebSocket("ws://127.0.0.1:8000/chat"); socket.onmessage = (e) => { let chat = document.getElementById("chat"); chat.innerHTML += "<div>" + e.data + "</div>"; chat.scrollTop = chat.scrollHeight; } function sendMsg(){ let input = document.getElementById("msg"); socket.send(input.value); input.value = ""; } </script> </body> </html>

5️⃣ Run the Chat Server

uvicorn chat_ws:app --reload

Then open chat.html in 2–3 browser tabs — chat live!


6️⃣ What You Learned

  • WebSocket protocol basics
  • Building async real-time communication in FastAPI
  • Maintaining active client pool
  • Broadcast messaging
  • Creating a front-end chat to test features

#10 Async Database with SQLModel

FastAPI Module 10 — Async Database with SQLModel

Module 10 — Async Database with SQLModel

In this module, we learn how to use SQLModel (from FastAPI's creator) to build a fully asynchronous database layer.


1️⃣ Install Dependencies

pip install sqlmodel aiosqlite

2️⃣ Create Database Models

We create a SQLModel model called Product.

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

3️⃣ Configure Async Engine & Session

from sqlmodel import SQLModel from sqlmodel.ext.asyncio.session import AsyncSession from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.orm import sessionmaker DATABASE_URL = "sqlite+aiosqlite:///./products.db" engine = create_async_engine(DATABASE_URL, echo=True) async_session = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False) async def init_db(): async with engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all)

4️⃣ FastAPI Startup Event (Create Tables)

from fastapi import FastAPI from database import init_db from routes import router app = FastAPI() @app.on_event("startup") async def on_startup(): await init_db() app.include_router(router)

5️⃣ CRUD Operations (Async)

We create full async CRUD in a router file.

from fastapi import APIRouter, Depends, HTTPException from sqlmodel.ext.asyncio.session import AsyncSession from sqlmodel import select from database import async_session from models import Product router = APIRouter() async def get_session(): async with async_session() as session: yield session @router.post("/products", response_model=Product) async def create_product(product: Product, session: AsyncSession = Depends(get_session)): session.add(product) await session.commit() await session.refresh(product) return product @router.get("/products") async def list_products(session: AsyncSession = Depends(get_session)): result = await session.exec(select(Product)) return result.all() @router.get("/products/{product_id}", response_model=Product) async def get_product(product_id: int, session: AsyncSession = Depends(get_session)): result = await session.exec(select(Product).where(Product.id == product_id)) product = result.first() if not product: raise HTTPException(404, "Product not found") return product @router.put("/products/{product_id}", response_model=Product) async def update_product(product_id: int, updated: Product, session: AsyncSession = Depends(get_session)): result = await session.exec(select(Product).where(Product.id == product_id)) product = result.first() if not product: raise HTTPException(404, "Product not found") product.name = updated.name product.price = updated.price session.add(product) await session.commit() await session.refresh(product) return product @router.delete("/products/{product_id}") async def delete_product(product_id: int, session: AsyncSession = Depends(get_session)): result = await session.exec(select(Product).where(Product.id == product_id)) product = result.first() if not product: raise HTTPException(404, "Product not found") await session.delete(product) await session.commit() return {"status": "deleted"}

6️⃣ Run the Server

uvicorn main:app --reload

7️⃣ Test CRUD in Swagger UI

Go to: ๐Ÿ‘‰ http://127.0.0.1:8000/docs Try: - ➕ Create product - ๐Ÿ“„ List products - ๐Ÿ” Get product - ✏️ Update product - ❌ Delete product

FAST API - Intro

 https://fastapi-hha68n1.gamma.site/