Python Backend, FastAPI & SQLite Cheat Sheet
Quick reference for Python backend development: REST status codes, httpx timeouts/retries, parameterized sqlite3 + transactions, FastAPI routes, Pydantic v2 schemas, Depends(), auth hashing/JWT, TestClient overrides, and Docker.
1 min readUpdated 2026-11-30
REST Status Codes
200 OK(GET/PATCH) ·201 Created(POST) ·204 No Content(DELETE)400/422Validation error ·401Unauthenticated ·403Forbidden ·404Not found ·409Conflict
httpx Client With Timeout & Retries
python
import httpx
with httpx.Client(base_url="https://api.example.com", timeout=5.0) as client:
res = client.get("/items", params={"page": 1})
res.raise_for_status()
data = res.json()Safe sqlite3 Queries & Atomic Transactions
python
import sqlite3
conn = sqlite3.connect("app.db", check_same_thread=False)
conn.row_factory = sqlite3.Row
# Parameterized ? query (NEVER f-strings!)
row = conn.execute("SELECT * FROM users WHERE email = ?", (email,)).fetchone()
# Atomic commit / automatic rollback on exception
with conn:
conn.execute("UPDATE accounts SET balance = balance - ? WHERE id = ?", (50, 1))
conn.execute("UPDATE accounts SET balance = balance + ? WHERE id = ?", (50, 2))FastAPI Routes, Pydantic v2 & Depends()
python
from fastapi import Depends, FastAPI, HTTPException, status
from pydantic import BaseModel, Field
app = FastAPI()
class TaskCreate(BaseModel):
title: str = Field(min_length=1, max_length=120)
class TaskUpdate(BaseModel):
title: str | None = None
completed: bool | None = None
def get_db():
conn = sqlite3.connect("app.db", check_same_thread=False)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
@app.post("/tasks", status_code=status.HTTP_201_CREATED)
def create_task(body: TaskCreate, db: sqlite3.Connection = Depends(get_db)):
...Salted Password Hashing & Constant-Time Check
python
import hashlib, hmac, secrets
def hash_password(pw: str) -> str:
salt = secrets.token_hex(16)
dk = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 200_000)
return f"{salt}${dk.hex()}"
def verify_password(pw: str, stored: str) -> bool:
salt, expected = stored.split("$", 1)
dk = hashlib.pbkdf2_hmac("sha256", pw.encode(), salt.encode(), 200_000)
return hmac.compare_digest(dk.hex(), expected)Testing with TestClient & dependency_overrides
python
from fastapi.testclient import TestClient
app.dependency_overrides[get_db] = override_get_db
with TestClient(app) as client:
assert client.get("/health").status_code == 200
app.dependency_overrides.clear()