FastAPI
FastAPI is not just another web framework. It is a fundamental rethink of what a Python API framework should feel like in 2026— one that makes the right thing the easy thing, gives you production-grade features out of the box, and does not ask you to write boilerplate that a machine can infer from code you already wrote.
This article goes deep. We cover the internals, the patterns, the gotchas, and end with an honest comparison against Flask, Django REST Framework, and other contenders.
Why FastAPI Exists
Flask came out in 2010. It was a breath of fresh air after Django — minimal, explicit, stay-out-of-your-way. But it was designed for a synchronous, pre-type-hints Python world. To get validation, serialization, and documentation out of Flask, you bolt on marshmallow, Flask-RESTful, apispec, Flask-Login — each with its own API, its own quirks, its own maintenance burden.
FastAPI was created by Sebastián Ramírez and first released in 2018. The core insight was: Python now has type hints (PEP 484, 3.5+) and Pydantic uses them to do runtime validation. If a framework is built from the ground up around type hints, it can eliminate entire categories of boilerplate automatically.
The result: you write Python functions with typed parameters. FastAPI infers the request schema, validates inputs, generates OpenAPI docs, and serializes responses — all from the same type annotations you’d write anyway for a good IDE experience.
The Foundation: ASGI, Starlette, and Uvicorn
Before writing a line of FastAPI code, understand the stack underneath it.
WSGI vs ASGI
Flask is a WSGI framework. WSGI (Web Server Gateway Interface, PEP 3333) is synchronous — one request, one thread, one response, done. This is fine for CPU-bound or DB-bound workloads where you’d use a thread pool anyway. But it cannot natively handle long-lived connections (WebSockets) or concurrent I/O without threads.
ASGI (Asynchronous Server Gateway Interface) is the async successor. Instead of a synchronous callable, an ASGI app is an async callable. This lets a single process handle thousands of concurrent connections using Python’s asyncio event loop — no threads required for I/O-bound work.
Difference between Synchronous and Asynchronous Programming:
Starlette
FastAPI is built on top of Starlette, which is the actual ASGI framework. Starlette handles routing, middleware, WebSockets, background tasks, static files, and test client. FastAPI wraps Starlette and adds the type-hint-driven parameter injection, Pydantic validation, and OpenAPI generation on top.
Uvicorn
Uvicorn is the ASGI server — the thing that actually listens on a port, accepts TCP connections, and runs your ASGI app. It is to FastAPI what Gunicorn is to Flask. For production, you typically run Gunicorn as the process manager with Uvicorn workers.
[Client] -> [Nginx] -> [Gunicorn] -> [Uvicorn Worker] -> [Starlette/FastAPI App]Install the full stack:
pip install fastapi uvicorn[standard] gunicornYour First FastAPI App
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello, World"}Run it:
uvicorn main:app --reload--reload watches for file changes and restarts automatically. Never use it in production.
Now open http://127.0.0.1:8000/docs. You get a fully interactive Swagger UI — for free, generated entirely from your code. Also available at /redoc for ReDoc UI and /openapi.json for the raw OpenAPI schema.
This is not a demo feature. The docs stay in sync with your code because they ARE generated from your code. There is no separate documentation to maintain.
Path Parameters
from fastapi import FastAPI
app = FastAPI()
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}FastAPI reads the {user_id} in the path and maps it to the user_id parameter of the function. The int type annotation means FastAPI will:
- Extract
user_idfrom the path - Attempt to convert it to
int - If conversion fails, return a 422 Unprocessable Entity with a clear error message automatically
GET /users/5 -> {"user_id": 5}
GET /users/abc -> 422 {"detail": [{"loc": ["path", "user_id"], "msg": "value is not a valid integer"}]}No try/except, no manual validation. The type annotation is the validation.
Path parameter types supported out of the box: int, float, str, bool, UUID, datetime, date, Decimal, and any Pydantic type.
Ordering matters: If you have both /users/me and /users/{user_id}, define /users/me first. FastAPI matches routes in definition order.
@app.get("/users/me")
def get_me():
return {"user": "current user"}
@app.get("/users/{user_id}")
def get_user(user_id: int):
return {"user_id": user_id}Query Parameters
Any function parameter that is not in the path pattern is treated as a query parameter:
@app.get("/items")
def list_items(
skip: int = 0,
limit: int = 10,
search: str | None = None,
active: bool = True
):
return {
"skip": skip,
"limit": limit,
"search": search,
"active": active
}
GET /items?skip=20&limit=5&search=phone&active=falseFastAPI handles the string-to-type coercion for all of them. bool conversion is smart: "false", "0", "no", "off" all become False. "true", "1", "yes", "on" all become True.
str | None = None marks a parameter as optional. Without a default value, it is required.
Pydantic Models: The Core of FastAPI
Pydantic is the engine that makes FastAPI’s validation work. A Pydantic model is a class that inherits from BaseModel and uses type annotations to define its fields. At instantiation time, Pydantic validates and coerces the input.
from pydantic import BaseModel, EmailStr, Field
from datetime import datetime
class UserCreate(BaseModel):
name: str = Field(min_length=1, max_length=100)
email: EmailStr
age: int = Field(ge=0, le=150)
bio: str | None = None
class UserResponse(BaseModel):
id: int
name: str
email: str
created_at: datetime
class Config:
from_attributes = True # Enables ORM mode (read from SQLAlchemy models)Field() lets you add constraints: min_length, max_length, ge (greater than or equal), le (less than or equal), gt, lt, regex, description, example.
EmailStr requires pip install pydantic[email] and validates email format.
Using these in a route:
@app.post("/users", response_model=UserResponse, status_code=201)
def create_user(user: UserCreate):
# user is already validated -- if we're here, the data is clean
new_user = save_to_db(user)
return new_userresponse_model=UserResponse tells FastAPI: filter and serialize the return value through UserResponse. Fields not in UserResponse are stripped. This is your output validation — you never accidentally leak internal fields.
Request Body, Path, and Query Together
FastAPI figures out where each parameter comes from based on its type:
from fastapi import FastAPI, Path, Query, Body
from pydantic import BaseModel
app = FastAPI()
class ItemUpdate(BaseModel):
name: str
price: float
@app.put("/shops/{shop_id}/items/{item_id}")
def update_item(
shop_id: int = Path(ge=1),
item_id: int = Path(ge=1),
currency: str = Query(default="INR", max_length=3),
item: ItemUpdate = Body(...)
):
return {
"shop_id": shop_id,
"item_id": item_id,
"currency": currency,
"item": item
}shop_idanditem_idcome from the pathcurrencycomes from the query stringitemcomes from the request body (JSON)
Path(), Query(), Body() are not just for validation — they also enrich the generated OpenAPI docs with descriptions, examples, and constraints.
Dependency Injection
This is one of FastAPI’s most powerful and underused features. The Depends system lets you declare reusable logic that FastAPI resolves and injects before calling your route function.
Common Pagination Pattern
from fastapi import Depends, Query
class PaginationParams:
def __init__(
self,
page: int = Query(default=1, ge=1),
per_page: int = Query(default=20, ge=1, le=100)
):
self.page = page
self.per_page = per_page
self.offset = (page - 1) * per_page
@app.get("/products")
def list_products(pagination: PaginationParams = Depends()):
return {
"page": pagination.page,
"per_page": pagination.per_page,
"offset": pagination.offset
}
@app.get("/orders")
def list_orders(pagination: PaginationParams = Depends()):
# Reuse the same pagination logic -- no copy-paste
return {"offset": pagination.offset}Authentication Dependency
from fastapi import Depends, HTTPException, Security
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
def get_current_user(
credentials: HTTPAuthorizationCredentials = Security(security)
) -> dict:
token = credentials.credentials
user = verify_jwt_token(token) # your JWT verification logic
if not user:
raise HTTPException(status_code=401, detail="Invalid token")
return user
@app.get("/profile")
def get_profile(current_user: dict = Depends(get_current_user)):
return {"user": current_user}
@app.delete("/profile")
def delete_profile(current_user: dict = Depends(get_current_user)):
return {"deleted": current_user["id"]}Dependencies can depend on other dependencies. FastAPI builds a dependency graph, resolves it in the correct order, and caches results within the same request scope by default.
Database Session Dependency
from sqlalchemy.orm import Session
from database import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/users/{user_id}")
def get_user(user_id: int, db: Session = Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
return useryield in a dependency turns it into a context manager. FastAPI runs the code before yield before the route, injects the yielded value, runs your route, then runs the code after yield for cleanup — even if an exception was raised.
Async Routes: When and Why
FastAPI supports both sync and async route functions. Understanding which to use matters.
# Sync -- runs in a thread pool executor
@app.get("/sync")
def sync_route():
result = some_blocking_db_call()
return result
# Async -- runs on the event loop
@app.get("/async")
async def async_route():
result = await some_async_db_call()
return resultWhen to use async: when your route does I/O — HTTP calls, database queries, file reads — using an async library (httpx, asyncpg, motor, aiofiles). The event loop can handle other requests while yours waits.
When to use sync: when your route does CPU-bound work, or when you’re using a synchronous library (like the standard requests library or synchronous SQLAlchemy). FastAPI runs sync routes in a thread pool automatically, so they don't block the event loop.
Get Vengadesa Boopathi’s stories in your inbox
Join Medium for free to get updates from this writer.
The mistake to avoid: never call blocking synchronous I/O inside an async route. This blocks the entire event loop.
import httpx
import requests
# WRONG -- blocks the event loop
@app.get("/wrong")
async def wrong():
response = requests.get("https://api.example.com/data") # blocks
return response.json()
# RIGHT -- async HTTP with httpx
@app.get("/right")
async def right():
async with httpx.AsyncClient() as client:
response = await client.get("https://api.example.com/data")
return response.json()Error Handling
HTTPException
from fastapi import HTTPException
@app.get("/users/{user_id}")
def get_user(user_id: int):
user = db.get(user_id)
if not user:
raise HTTPException(
status_code=404,
detail={"error": "User not found", "user_id": user_id}
)
return userdetail can be a string or a dict — FastAPI serializes it as JSON automatically.
Custom Exception Handlers
from fastapi import Request
from fastapi.responses import JSONResponse
class InsufficientFundsError(Exception):
def __init__(self, balance: float, required: float):
self.balance = balance
self.required = required
@app.exception_handler(InsufficientFundsError)
async def insufficient_funds_handler(request: Request, exc: InsufficientFundsError):
return JSONResponse(
status_code=402,
content={
"error": "Insufficient Funds",
"balance": exc.balance,
"required": exc.required,
"shortfall": exc.required - exc.balance
}
)
@app.post("/purchase")
def make_purchase(amount: float):
balance = get_user_balance()
if balance < amount:
raise InsufficientFundsError(balance=balance, required=amount)
return {"status": "success"}Override Default Validation Error Handler
FastAPI returns a 422 with Pydantic’s error format by default. You can override it:
from fastapi.exceptions import RequestValidationError
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
errors = []
for error in exc.errors():
errors.append({
"field": ".".join(str(loc) for loc in error["loc"]),
"message": error["msg"],
"type": error["type"]
})
return JSONResponse(
status_code=422,
content={"error": "Validation Failed", "details": errors}
)Middleware
import time
import uuid
from fastapi import Request
@app.middleware("http")
async def request_middleware(request: Request, call_next):
request_id = str(uuid.uuid4())
start_time = time.time()
request.state.request_id = request_id
response = await call_next(request)
duration_ms = round((time.time() - start_time) * 1000, 2)
response.headers["X-Request-ID"] = request_id
response.headers["X-Response-Time"] = f"{duration_ms}ms"
print(f"{request.method} {request.url.path} -> {response.status_code} ({duration_ms}ms)")
return responseFor CORS:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["https://yourfrontend.com"],
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH"],
allow_headers=["Authorization", "Content-Type"]
)For compression:
from fastapi.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=1000)Routers: Structuring a Real Application
project/
├── main.py
├── routers/
│ ├── __init__.py
│ ├── users.py
│ └── products.py
├── models/
│ ├── user.py
│ └── product.py
├── dependencies.py
└── database.pyrouters/users.py:
from fastapi import APIRouter, Depends, HTTPException
from dependencies import get_db, get_current_user
router = APIRouter(
prefix="/users",
tags=["users"],
dependencies=[Depends(get_current_user)]
)
@router.get("/")
def list_users(db=Depends(get_db)):
return db.query(User).all()
@router.get("/{user_id}")
def get_user(user_id: int, db=Depends(get_db)):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="Not found")
return user
@router.post("/", status_code=201)
def create_user(data: UserCreate, db=Depends(get_db)):
user = User(**data.dict())
db.add(user)
db.commit()
db.refresh(user)
return usermain.py:
from fastapi import FastAPI
from routers import users, products
app = FastAPI(
title="My API",
description="Production API built with FastAPI",
version="1.0.0"
)
app.include_router(users.router)
app.include_router(products.router)tags=["users"] groups routes in the Swagger UI. prefix="/users" means you don't repeat /users in every route definition.
Lifespan Events: Startup and Shutdown
FastAPI’s modern way to handle startup/shutdown logic (DB connections, loading ML models, etc.):
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# Runs before app starts accepting requests
print("Starting up...")
await database.connect()
load_ml_model()
yield # App runs here
# Runs when app is stopping
print("Shutting down...")
await database.disconnect()
app = FastAPI(lifespan=lifespan)This replaces the older @app.on_event("startup") decorator which is now deprecated.
Background Tasks
For work that should happen after the response is sent:
from fastapi import BackgroundTasks
def send_welcome_email(email: str, name: str):
# Runs after the response is already sent
email_service.send(
to=email,
subject="Welcome!",
body=f"Hello {name}, welcome aboard."
)
@app.post("/users", status_code=201)
def create_user(user: UserCreate, background_tasks: BackgroundTasks):
new_user = db.create(user)
background_tasks.add_task(send_welcome_email, user.email, user.name)
return new_user # Response sent immediately; email sends afterFor heavier background work (long-running jobs), use a proper task queue like Celery + Redis instead.
WebSockets
FastAPI supports WebSockets natively via Starlette:
from fastapi import WebSocket, WebSocketDisconnect
class ConnectionManager:
def __init__(self):
self.active: list[WebSocket] = []
async def connect(self, ws: WebSocket):
await ws.accept()
self.active.append(ws)
def disconnect(self, ws: WebSocket):
self.active.remove(ws)
async def broadcast(self, message: str):
for connection in self.active:
await connection.send_text(message)
manager = ConnectionManager()
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(ws: WebSocket, client_id: str):
await manager.connect(ws)
try:
while True:
data = await ws.receive_text()
await manager.broadcast(f"{client_id}: {data}")
except WebSocketDisconnect:
manager.disconnect(ws)
await manager.broadcast(f"{client_id} left")Real-time chat broadcast in under 30 lines. Flask cannot do this natively at all.
Consuming External APIs from FastAPI
Since FastAPI is async-native, use httpx instead of requests for outbound HTTP calls. requests is synchronous and blocks the event loop inside async routes.
pip install httpxBasic GET Request
import httpx
from fastapi import FastAPI, HTTPException
app = FastAPI()
@app.get("/weather/{city}")
async def get_weather(city: str):
async with httpx.AsyncClient() as client:
response = await client.get(
"https://api.openweathermap.org/data/2.5/weather",
params={"q": city, "appid": "your_api_key", "units": "metric"},
timeout=5.0
)
if response.status_code == 404:
raise HTTPException(status_code=404, detail=f"City not found")
response.raise_for_status()
return response.json()Reusing a Client with Lifespan (Production Pattern)
Opening a new AsyncClient on every request creates a new connection pool each time. The right pattern is one client at startup, reused across all requests.
import httpx
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends
http_client: httpx.AsyncClient = None
@asynccontextmanager
async def lifespan(app: FastAPI):
global http_client
http_client = httpx.AsyncClient(
timeout=httpx.Timeout(connect=3.0, read=10.0, write=5.0, pool=2.0),
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)
)
yield
await http_client.aclose()
app = FastAPI(lifespan=lifespan)
def get_http_client() -> httpx.AsyncClient:
return http_client
@app.get("/github/{username}")
async def get_github_user(
username: str,
client: httpx.AsyncClient = Depends(get_http_client)
):
response = await client.get(
f"https://api.github.com/users/{username}",
headers={"Accept": "application/vnd.github.v3+json"}
)
if response.status_code == 404:
raise HTTPException(status_code=404, detail="GitHub user not found")
response.raise_for_status()
return response.json()Parallel API Calls with asyncio.gather
One of the biggest wins of async: fire multiple API calls simultaneously and wait for all together. Sequential requests would take 300ms x 3 = 900ms. asyncio.gather runs them concurrently so total time is roughly the slowest single call, around 300ms.
import asyncio
import httpx
from fastapi import FastAPI
app = FastAPI()
@app.get("/dashboard/{user_id}")
async def get_dashboard(user_id: int):
async with httpx.AsyncClient(timeout=10.0) as client:
profile_task = client.get(f"https://api.example.com/users/{user_id}")
orders_task = client.get(f"https://api.example.com/orders?user={user_id}")
notifs_task = client.get(f"https://api.example.com/notifications/{user_id}")
profile, orders, notifs = await asyncio.gather(
profile_task, orders_task, notifs_task
)
return {
"profile": profile.json(),
"orders": orders.json(),
"notifications": notifs.json()
}Error Handling for Outbound Calls
import httpx
from fastapi import HTTPException
async def call_external_api(url: str, client: httpx.AsyncClient) -> dict:
try:
response = await client.get(url, timeout=5.0)
response.raise_for_status()
return response.json()
except httpx.TimeoutException:
raise HTTPException(status_code=504, detail="External API timed out")
except httpx.HTTPStatusError as e:
raise HTTPException(
status_code=e.response.status_code,
detail=f"External API error: {e.response.text}"
)
except httpx.RequestError as e:
raise HTTPException(status_code=502, detail=f"Could not reach external API: {str(e)}")POST with Headers and Auth to External APIs
@app.post("/send-notification")
async def send_notification(user_id: int, message: str):
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.notifications.com/send",
json={"user_id": user_id, "message": message},
headers={
"Authorization": "Bearer your_token_here",
"Content-Type": "application/json"
},
timeout=5.0
)
response.raise_for_status()
return {"status": "sent", "response": response.json()}Testing FastAPITestClient
FastAPI ships with a TestClient from Starlette (wraps httpx):
from fastapi.testclient import TestClient
from main import app
client = TestClient(app)
def test_create_user():
response = client.post(
"/users",
json={"name": "Venki", "email": "v@example.com", "age": 25}
)
assert response.status_code == 201
data = response.json()
assert data["name"] == "Venki"
assert "id" in data
def test_invalid_email():
response = client.post(
"/users",
json={"name": "Venki", "email": "not-an-email", "age": 25}
)
assert response.status_code == 422
def test_user_not_found():
response = client.get("/users/99999")
assert response.status_code == 404For async tests with pytest-asyncio:
import pytest
import httpx
from main import app
@pytest.mark.asyncio
async def test_async_endpoint():
async with httpx.AsyncClient(app=app, base_url="http://test") as client:
response = await client.get("/async-endpoint")
assert response.status_code == 200A Production-Ready FastAPI Template
import time
import uuid
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from fastapi.middleware.gzip import GZipMiddleware
LOG_FORMAT = "%(asctime)s | %(levelname)s | %(name)s | %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Starting up...")
# await db.connect()
yield
logger.info("Shutting down...")
# await db.disconnect()
app = FastAPI(
title="My API",
description="Production-ready FastAPI application",
version="1.0.0",
lifespan=lifespan,
docs_url="/docs",
redoc_url="/redoc"
)
app.add_middleware(GZipMiddleware, minimum_size=1000)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"]
)
@app.middleware("http")
async def request_middleware(request: Request, call_next):
request_id = str(uuid.uuid4())
request.state.request_id = request_id
start = time.time()
response = await call_next(request)
duration_ms = round((time.time() - start) * 1000, 2)
response.headers["X-Request-ID"] = request_id
response.headers["X-Response-Time"] = f"{duration_ms}ms"
logger.info(
f"rid={request_id} method={request.method} "
f"path={request.url.path} status={response.status_code} "
f"duration_ms={duration_ms}"
)
return response
@app.exception_handler(RequestValidationError)
async def validation_error_handler(request: Request, exc: RequestValidationError):
errors = [
{
"field": ".".join(str(l) for l in e["loc"]),
"message": e["msg"],
"type": e["type"]
}
for e in exc.errors()
]
return JSONResponse(status_code=422, content={"error": "Validation Failed", "details": errors})
@app.exception_handler(Exception)
async def unhandled_exception_handler(request: Request, exc: Exception):
logger.exception(f"Unhandled exception on {request.method} {request.url.path}")
return JSONResponse(
status_code=500,
content={
"error": "Internal Server Error",
"request_id": request.state.request_id
}
)
@app.get("/health", tags=["system"])
def health_check():
return {"status": "ok"}
# app.include_router(users.router)
# app.include_router(products.router)Run in production:
gunicorn main:app \
--workers 4 \
--worker-class uvicorn.workers.UvicornWorker \
--bind 0.0.0.0:8000 \
--timeout 60 \
--access-logfile -FastAPI vs Flask vs Django REST Framework vs Others
FastAPI vs Flask
Flask’s advantage is its age. If you search for a Flask extension to do something, it probably exists. FastAPI’s ecosystem is younger but growing rapidly. If you’re starting a new project today with no legacy constraints, FastAPI is the better choice in almost every scenario.
FastAPI vs Django REST Framework (DRF)
DRF is the right choice when you are building a Django application that needs REST endpoints — you already have the ORM, migrations, admin, and auth. Adding DRF is natural. FastAPI is the right choice when you want a pure API backend with no framework opinions on ORM or database.
FastAPI vs Express (Node.js)
Choosing between these is mostly a language preference call. If your team knows Python, FastAPI. If they know JavaScript/TypeScript, Express or Fastify.
FastAPI vs Litestar
Litestar is the closest competitor to FastAPI in the Python async world. Both are ASGI, both use Pydantic, both generate OpenAPI docs. Litestar has a more opinionated architecture with better built-in dependency injection patterns and a slightly steeper learning curve. FastAPI has a larger community and far more third-party tutorials. For most teams, FastAPI is the better-supported choice today.
When NOT to Use FastAPI
- You need Django admin, Django ORM, or Django’s full-stack features — use Django + DRF
- You have an existing Flask codebase with years of extensions — migration cost may not be worth it
- Your team is a Node.js shop — pick Fastify or Express
- You’re building a simple internal tool with minimal endpoints — Flask’s simplicity may actually be an advantage
- You need gRPC as your primary protocol — consider grpcio directly
The Bottom Line
FastAPI earns its popularity. It is not hype. The combination of Pydantic validation, automatic OpenAPI docs, native async, and a clean dependency injection system produces APIs that are faster to write, harder to break, and easier to document than anything Python had before it.
The learning curve is real — you need to understand async/await, Pydantic models, and dependency injection to use it well. But once those click, going back to writing manual validation and maintaining separate API documentation feels like a step backward.
Start with the production template above. Add SQLAlchemy + alembic for your database. Add python-jose or PyJWT for JWT auth. Add pytest + httpx for tests. You will have a production-grade API stack in an afternoon.
This is part of a series on Python API development. The previous article covers APIs from first principles — TCP handshakes, HTTP internals, Flask deep dive, and common API design mistakes.






