FastAPI Cheatsheet
Quick reference for common FastAPI patterns. Keep this open during your interview.
Basic Routes
Routes
1from fastapi import FastAPI23app = FastAPI()45# Basic GET6@app.get("/items")7def get_items():8 return [{"id": 1, "name": "Item"}]910# Path parameter11@app.get("/items/{item_id}")12def get_item(item_id: int):13 return {"id": item_id}1415# Query parameter16@app.get("/items")17def get_items(skip: int = 0, limit: int = 10):18 return items[skip : skip + limit]1920# Multiple query params21@app.get("/search")22def search(q: str, category: str | None = None):23 return {"query": q, "category": category}
Request Body with Pydantic
Pydantic Models
1from pydantic import BaseModel23class ItemCreate(BaseModel):4 name: str5 price: float6 description: str | None = None78class ItemResponse(BaseModel):9 id: int10 name: str11 price: float1213 class Config:14 from_attributes = True # For SQLAlchemy1516@app.post("/items", response_model=ItemResponse)17def create_item(item: ItemCreate):18 # item.name, item.price are validated19 return {"id": 1, **item.model_dump()}
HTTP Methods
CRUD Methods
1@app.get("/items") # Read / List2@app.post("/items") # Create3@app.put("/items/{id}") # Full Update4@app.patch("/items/{id}") # Partial Update5@app.delete("/items/{id}")# Delete
Error Handling
HTTPException
1from fastapi import HTTPException23@app.get("/items/{item_id}")4def get_item(item_id: int):5 item = db.query(Item).filter(Item.id == item_id).first()6 if not item:7 raise HTTPException(8 status_code=404,9 detail="Item not found"10 )11 return item1213# Common status codes:14# 200 - OK15# 201 - Created16# 400 - Bad Request17# 401 - Unauthorized18# 403 - Forbidden19# 404 - Not Found20# 422 - Validation Error (automatic)
CORS (CRITICAL!)
CORS Setup
1from fastapi.middleware.cors import CORSMiddleware23app = FastAPI()45# Add this IMMEDIATELY after creating app6app.add_middleware(7 CORSMiddleware,8 allow_origins=["http://localhost:3000"], # Frontend URL9 allow_credentials=True,10 allow_methods=["*"],11 allow_headers=["*"],12)
Database with SQLAlchemy
SQLAlchemy Setup
1from sqlalchemy import create_engine, Column, Integer, String2from sqlalchemy.ext.declarative import declarative_base3from sqlalchemy.orm import sessionmaker45# Setup6DATABASE_URL = "sqlite:///./app.db"7engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})8SessionLocal = sessionmaker(bind=engine)9Base = declarative_base()1011# Model12class Item(Base):13 __tablename__ = "items"14 id = Column(Integer, primary_key=True, index=True)15 name = Column(String, index=True)1617Base.metadata.create_all(bind=engine)1819# Dependency20def get_db():21 db = SessionLocal()22 try:23 yield db24 finally:25 db.close()2627# Usage in route28from fastapi import Depends29from sqlalchemy.orm import Session3031@app.get("/items")32def get_items(db: Session = Depends(get_db)):33 return db.query(Item).all()
Common SQLAlchemy Queries
SQLAlchemy Queries
1# Get all2items = db.query(Item).all()34# Get one by ID5item = db.query(Item).filter(Item.id == item_id).first()67# Create8new_item = Item(name="New")9db.add(new_item)10db.commit()11db.refresh(new_item) # Get the generated ID1213# Update14item.name = "Updated"15db.commit()1617# Delete18db.delete(item)19db.commit()2021# Filter with multiple conditions22items = db.query(Item).filter(23 Item.price > 10,24 Item.category == "electronics"25).all()2627# Order by28items = db.query(Item).order_by(Item.created_at.desc()).all()2930# Limit31items = db.query(Item).limit(10).offset(20).all()
WebSockets
WebSocket Endpoint
1from fastapi import WebSocket, WebSocketDisconnect23@app.websocket("/ws")4async def websocket_endpoint(websocket: WebSocket):5 await websocket.accept()6 try:7 while True:8 data = await websocket.receive_json()9 await websocket.send_json({"echo": data})10 except WebSocketDisconnect:11 print("Client disconnected")
Running the Server
Terminal
1# Development (auto-reload)2uvicorn main:app --reload --port 800034# Production5uvicorn main:app --host 0.0.0.0 --port 800067# With multiple workers8uvicorn main:app --workers 4