Advertisement
Verified Partner
Enterprise Cloud Infrastructure, GPU Clusters & AI APIs
Deploy high-throughput inference and quant trading pipelines with ultra-low latency.
Explore Platform β†’

FastAPI Cheatsheet: Routes, Parameters, Pydantic, Dependencies and Errors

FastAPI essentials in one page: routes for every HTTP method, typed parameters with validation, Pydantic request and response models, dependencies, routers and error handling.

πŸ§ͺ
Run & Edit this Code Live in Browser Zero setup required. Supports Python 3, modern JavaScript, and SQL.
β–Ά Run in Playground β†’

1. Your First App and the Core Routes

Install with pip install fastapi uvicorn, run with uvicorn main:app --reload, and document everything for free at /docs. The HTTP method decorators mirror REST verbs.

CODE SNIPPET
from fastapi import FastAPI, status

app = FastAPI(title="Shop API", version="1.0.0")

@app.get("/health")
def health():
    return {"status": "ok"}

@app.get("/items/{item_id}")
def read_item(item_id: int):
    return {"item_id": item_id}

@app.post("/items", status_code=status.HTTP_201_CREATED)
def create_item(item: dict):
    return item

@app.put("/items/{item_id}")   # full replace
@app.patch("/items/{item_id}") # partial update
@app.delete("/items/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_item(item_id: int):
    return None

2. Parameters and Validation

Type hints are validation: FastAPI converts and checks incoming data, and returns a 422 with details when it fails. Query, Path, Header and Body add defaults and constraints.

PatternWhat it declares
def f(q: str | None = None)Optional query parameter
def f(q: str = Query("fixed", min_length=3, max_length=50))Query with defaults and length constraints
def f(item_id: int = Path(ge=1))Path parameter that must be β‰₯ 1
def f(tags: list[str] = Query([]))Repeated query parameter: ?tags=a&tags=b
def f(x_token: str = Header(...))Required header value
def f(session: str = Cookie(None))Cookie value
async def f(file: UploadFile = File(...))Uploaded file (streamed, not loaded whole)
def f(payload: dict = Body(...))Raw JSON body without a model
Advertisement
Verified Partner
Quantitative Trading Systems & 30 AI Business Blueprints
Build predictable monthly recurring revenue with retainers & automated bots.
View Blueprints β†’

3. Pydantic Models: Requests and Responses

Models define the contract in both directions. response_model filters what leaves the API, so internal fields (hashes, costs) never leak by accident.

CODE SNIPPET
from pydantic import BaseModel, Field

class ItemIn(BaseModel):
    name: str = Field(min_length=1, max_length=80)
    price: float = Field(gt=0)
    tags: list[str] = []

class ItemOut(BaseModel):
    id: int
    name: str
    price: float
    tags: list[str]

@app.post("/items", response_model=ItemOut, status_code=201)
def create_item(item: ItemIn):
    saved = save_to_db(item)   # returns dict/object with extra fields
    return saved               # only ItemOut fields are exposed

4. Dependencies, Routers and Errors

Dependencies inject shared logic (auth, database sessions) into any route. Routers split big APIs by domain, and HTTPException produces clean, consistent error responses.

CODE SNIPPET
from fastapi import Depends, HTTPException, APIRouter

def get_db():
    db = SessionLocal()
    try:
        yield db               # value injected into the route
    finally:
        db.close()             # always cleaned up

router = APIRouter(prefix="/items", tags=["items"])

@router.get("/{item_id}")
def read_item(item_id: int, db=Depends(get_db)):
    item = db.get(Item, item_id)
    if item is None:
        raise HTTPException(status_code=404, detail="Item not found")
    return item

app.include_router(router)

πŸš€ Associated Learning Path & Monetization Blueprints

πŸ“š Comprehensive Pillar Guide

Python FastAPI Microservices: Build Production APIs

Grow this cheatsheet into a full microservices architecture with testing and deployment.

Read Full Guide β†’
πŸ’° Monetizable AI Blueprint

Database-to-API Synthesizer

Turn client databases into documented, billable APIs with FastAPI.

Read Blueprint β†’
πŸ“ˆ Topic Hub: Python & AI Development β†’

Need another cheat sheet?

We add new reference guides every week based on community requests.

Request a Cheatsheet β†’