FastAPI 12-Module Course — How to run Modules 1 → 12 (step-by-step)
Module 1 — Setup & Hello World
- 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
- Install FastAPI and Uvicorn.
pip install fastapi uvicorn
- Create
main.pywith the Hello World app.
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def read_root():
return {"message": "Hello, FastAPI!"}
- 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
- 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}
- 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
- Create
module3.pyand 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}
- 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
- Use
response_modelto 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
- 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
- Learn
Dependsfor 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)
- Install required packages for JWT and password hashing:
pip install python-jose passlib[bcrypt]
- 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
- Use FastAPI's
BackgroundTasksfor 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
- Use
UploadFileto 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)}
- 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
- Install SQLModel and async driver:
pip install sqlmodel aiosqlite
- 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)
- 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)
- 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
- 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