Skip to content
Streak:0Loading your progress…Sign in

Module 6 · Lesson 3 of 3

REST design & FastAPI

Routes, status codes, pagination and error shapes — then how FastAPI does it for you. ~30 min

Lesson notes

FastAPI in 15 lines (run locally with `uv run fastapi dev main.py`)
from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel

app = FastAPI()

class TodoIn(BaseModel):
    title: str

@app.get("/v1/todos")
def list_todos(limit: int = Query(20, le=100), cursor: str | None = None):
    ...

@app.post("/v1/todos", status_code=201)
def create_todo(body: TodoIn):
    ...

@app.get("/v1/todos/{todo_id}")
def get_todo(todo_id: int):
    raise HTTPException(status_code=404, detail="todo not found")

FastAPI reads your type hints: path params, query params with limits, and request bodies are validated by Pydantic automatically, invalid input returns 422, and you get OpenAPI docs at /docs for free. Dependencies (Depends(get_current_user)) inject auth, DB sessions and config — testable via app.dependency_overrides.

Practice

  1. 1. Build a tiny router

    hard50 XP

    Implement class App with decorator methods get(path) and post(path) that register handlers, and handle(method, path, body=None) -> (status, dict). Paths may contain {name} params passed to the handler as keyword strings. POST handlers receive body too. Unknown path → (404, {"error": "not found"}); known path, wrong method → (405, {"error": "method not allowed"}). A handler raising KeyError → (404, …); ValueError → (400, {"error": str(e)}). Handlers return (status, dict).

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor