FastAPI Cheatsheet — Complete Quick Reference (2026)
In this tutorial, you'll learn about FastAPI Cheatsheet. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
FastAPI is a modern Python web framework for building APIs with automatic OpenAPI documentation, Pydantic validation, async support, and Dependency Injection.
Path Operations
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
@app.post("/items", status_code=201)
async def create_item(item: Item):
return item
@app.put("/items/{item_id}")
@app.patch("/items/{item_id}")
@app.delete("/items/{item_id}")
Pydantic Models
from pydantic import BaseModel, Field, EmailStr
class Item(BaseModel):
name: str = Field(..., min_length=1, max_length=100)
price: float = Field(..., gt=0)
description: str | None = None
tax: float | None = None
class User(BaseModel):
email: EmailStr
password: str = Field(..., min_length=8)
# response model
@app.get("/items", response_model=list[Item])
async def list_items(): ...
Path & Query Parameters
from fastapi import Path, Query
@app.get("/items/{item_id}")
async def read(
item_id: int = Path(..., ge=1, title="Item ID"),
q: str | None = Query(None, max_length=50, pattern=r"^\w+$"),
page: int = Query(1, ge=1),
size: int = Query(20, ge=1, le=100),
): ...
Dependency Injection
from fastapi import Depends, HTTPException
async def get_db():
db = Database()
try:
yield db
finally:
db.close()
def verify_token(token: str = Header(...)):
if token != "secret":
raise HTTPException(401)
return token
@app.get("/users")
async def get_users(
db=Depends(get_db),
_=Depends(verify_token),
limit: int = Query(10),
): ...
Authentication
from fastapi.security import HTTPBearer, OAuth2PasswordBearer
from jose import JWTError, jwt
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except JWTError:
raise HTTPException(401)
return payload.get("sub")
@app.get("/me")
async def read_users_me(current_user = Depends(get_current_user)):
return current_user
Request Body & Forms
from fastapi import Form, File, UploadFile
@app.post("/login")
async def login(username: str = Form(...), password: str = Form(...)): ...
@app.post("/upload")
async def upload(file: UploadFile = File(...)): ...
WebSocket
from fastapi import WebSocket, WebSocketDisconnect
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Echo: {data}")
except WebSocketDisconnect:
print("client disconnected")
Background Tasks
from fastapi import BackgroundTasks
def send_email(email: str, body: str): ...
@app.post("/register")
async def register(user: User, tasks: BackgroundTasks):
tasks.add_task(send_email, user.email, "Welcome!")
return {"message": "registered"}
OpenAPI Customization
from fastapi.openapi.utils import get_openapi
app.title = "My API"
app.description = "API for **awesome** features"
app.version = "2.0.0"
app.openapi_tags = [
{"name": "users", "description": "User operations"},
]
@app.get("/openapi.json", include_in_schema=False)
async def custom_openapi(): ...
CORS & Middleware
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
Must-Know Items
- Use
response_modelto control what data is returned (hides secrets, validates output) - Dependencies are cached within the same request scope by default
Body(),Query(),Path()provide validation metadata and OpenAPI docsasync deffor I/O-bound routes; regulardeffor CPU-bound (runs in threadpool)- Pydantic v2 with
BaseModelis significantly faster than v1 - Use
HTTPExceptionfor standard error responses (auto-documented in OpenAPI) - Lifespan context manager replaces old startup/shutdown events in FastAPI ≥ 0.89
{{< faq "What is the difference between async def and def in FastAPI?">}}async def runs on the main event loop and is ideal for I/O-bound operations (database queries, HTTP calls, file reads). Regular def runs in a threadpool and is suitable for CPU-bound operations. FastAPI automatically handles the threading — you don't need to manage it manually.{{< /faq >}}
{{< faq "How does dependency injection work in FastAPI?">}}Dependencies are regular functions declared with Depends(). FastAPI resolves them automatically, handles sub-dependencies, and caches results within a request. Dependencies can return values, perform validation, handle authentication, manage database sessions, and clean up resources using yield.{{< /faq >}}
See full FastAPI tutorials for building production APIs.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro