Python FastAPI Cheat Sheet

Quick reference guide for Python FastAPI: Path operations, Pydantic v2 schemas, dependency injection, and async.

Languages
fastapi
python
backend

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python based on standard Python type hints and Pydantic.

App Setup & Path Operation Decorators

python
from fastapi import FastAPI, HTTPException, status, Query, Depends
from pydantic import BaseModel, EmailStr
from typing import List, Optional

app = FastAPI(title="User Service API", version="1.0.0")

# Request / Response Pydantic Schema
class UserCreate(BaseModel):
    name: str
    email: EmailStr
    age: Optional[int] = None

class UserResponse(UserCreate):
    id: int

# GET Endpoint with Query Parameter validation
@app.get("/users", response_model=List[UserResponse])
async def get_users(limit: int = Query(10, ge=1, le=100)):
    return []

# POST Endpoint with Status Code & Exception handling
@app.post("/users", response_model=UserResponse, status_code=status.HTTP_201_CREATED)
async def create_user(user: UserCreate):
    if user.email == "banned@example.com":
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Email address is restricted"
        )
    return {**user.model_dump(), "id": 1}

Dependency Injection (`Depends`)

Dependencies reuse logic, enforce security auth, and open database sessions seamlessly.

python
async def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
    return {"q": q, "skip": skip, "limit": limit}

@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
    return commons

Essential FastAPI & Uvicorn CLI Commands

Table
CommandPurpose / Action
uvicorn main:app --reloadStart Uvicorn development server with hot-reload enabled
uvicorn main:app --host 0.0.0.0 --port 8000Bind Uvicorn server to external network interface
fastapi dev main.pyStart FastAPI native CLI dev server (FastAPI 0.111+)

Common Pitfalls & Tips

[!WARNING] Defining a blocking, synchronous def function without async causes FastAPI to execute it inside an external threadpool. Use async def for non-blocking async I/O.

[!TIP] FastAPI automatically generates interactive OpenAPI documentation at /docs (Swagger UI) and /redoc based on your Pydantic schemas.