FastAPI Cheatsheet

Quick reference for common FastAPI patterns. Keep this open during your interview.

Basic Routes

Routes
1from fastapi import FastAPI
2
3app = FastAPI()
4
5# Basic GET
6@app.get("/items")
7def get_items():
8 return [{"id": 1, "name": "Item"}]
9
10# Path parameter
11@app.get("/items/{item_id}")
12def get_item(item_id: int):
13 return {"id": item_id}
14
15# Query parameter
16@app.get("/items")
17def get_items(skip: int = 0, limit: int = 10):
18 return items[skip : skip + limit]
19
20# Multiple query params
21@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 BaseModel
2
3class ItemCreate(BaseModel):
4 name: str
5 price: float
6 description: str | None = None
7
8class ItemResponse(BaseModel):
9 id: int
10 name: str
11 price: float
12
13 class Config:
14 from_attributes = True # For SQLAlchemy
15
16@app.post("/items", response_model=ItemResponse)
17def create_item(item: ItemCreate):
18 # item.name, item.price are validated
19 return {"id": 1, **item.model_dump()}

HTTP Methods

CRUD Methods
1@app.get("/items") # Read / List
2@app.post("/items") # Create
3@app.put("/items/{id}") # Full Update
4@app.patch("/items/{id}") # Partial Update
5@app.delete("/items/{id}")# Delete

Error Handling

HTTPException
1from fastapi import HTTPException
2
3@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 item
12
13# Common status codes:
14# 200 - OK
15# 201 - Created
16# 400 - Bad Request
17# 401 - Unauthorized
18# 403 - Forbidden
19# 404 - Not Found
20# 422 - Validation Error (automatic)

CORS (CRITICAL!)

CORS Setup
1from fastapi.middleware.cors import CORSMiddleware
2
3app = FastAPI()
4
5# Add this IMMEDIATELY after creating app
6app.add_middleware(
7 CORSMiddleware,
8 allow_origins=["http://localhost:3000"], # Frontend URL
9 allow_credentials=True,
10 allow_methods=["*"],
11 allow_headers=["*"],
12)

Database with SQLAlchemy

SQLAlchemy Setup
1from sqlalchemy import create_engine, Column, Integer, String
2from sqlalchemy.ext.declarative import declarative_base
3from sqlalchemy.orm import sessionmaker
4
5# Setup
6DATABASE_URL = "sqlite:///./app.db"
7engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
8SessionLocal = sessionmaker(bind=engine)
9Base = declarative_base()
10
11# Model
12class Item(Base):
13 __tablename__ = "items"
14 id = Column(Integer, primary_key=True, index=True)
15 name = Column(String, index=True)
16
17Base.metadata.create_all(bind=engine)
18
19# Dependency
20def get_db():
21 db = SessionLocal()
22 try:
23 yield db
24 finally:
25 db.close()
26
27# Usage in route
28from fastapi import Depends
29from sqlalchemy.orm import Session
30
31@app.get("/items")
32def get_items(db: Session = Depends(get_db)):
33 return db.query(Item).all()

Common SQLAlchemy Queries

SQLAlchemy Queries
1# Get all
2items = db.query(Item).all()
3
4# Get one by ID
5item = db.query(Item).filter(Item.id == item_id).first()
6
7# Create
8new_item = Item(name="New")
9db.add(new_item)
10db.commit()
11db.refresh(new_item) # Get the generated ID
12
13# Update
14item.name = "Updated"
15db.commit()
16
17# Delete
18db.delete(item)
19db.commit()
20
21# Filter with multiple conditions
22items = db.query(Item).filter(
23 Item.price > 10,
24 Item.category == "electronics"
25).all()
26
27# Order by
28items = db.query(Item).order_by(Item.created_at.desc()).all()
29
30# Limit
31items = db.query(Item).limit(10).offset(20).all()

WebSockets

WebSocket Endpoint
1from fastapi import WebSocket, WebSocketDisconnect
2
3@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 8000
3
4# Production
5uvicorn main:app --host 0.0.0.0 --port 8000
6
7# With multiple workers
8uvicorn main:app --workers 4