FastAPI
FastAPI is an ASGI framework for HTTP APIs. You declare path operations with type hints; Pydantic validates bodies; OpenAPI docs are generated. Async and sync views are both supported.
Detailed Explanation
A FastAPI app is a collection of decorated functions. @app.get("/orders/{order_id}") plus async def get_order(order_id: str) is a route. Query, path, header, and body parameters are function arguments. A Pydantic model as a parameter is a JSON body. A model as a response_model filters the output.
Validation failures become 422 with a structured error. That is the usual reason to pick FastAPI: the boundary is typed and documented without a separate schema file. You can still write wrong types (dict for everything) and lose the benefit.
Depends is the DI system. A dependency can be a database session, the current user, or a settings object. It can yield for teardown. Tests override dependencies with app.dependency_overrides.
FastAPI runs on an ASGI server (uvicorn, hypercorn). async def views may await async I/O. def views run in a threadpool so they do not block the loop. Do not call requests inside async def. Do not run CPU-heavy work on the loop.
Background tasks, middleware, CORS (CORSMiddleware), and lifespan (lifespan= or on_event legacy) cover process setup. Lifespan is where you open a connection pool and close it.
FastAPI is not a full stack. There is no admin, no ORM. Pair it with SQLAlchemy, SQLModel, or raw SQL. For HTML-first apps, Flask or Django may still be simpler.
Code Examples
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
app = FastAPI()
class Order(BaseModel):
id: str
cents: int
ORDERS = {"11": Order(id="11", cents=2500)}
@app.get("/orders/{order_id}", response_model=Order)
def get_order(order_id: str) -> Order:
try:
return ORDERS[order_id]
except KeyError:
raise HTTPException(status_code=404, detail="not found")from fastapi import Depends
def get_db():
db = {"ok": True}
try:
yield db
finally:
db["ok"] = FalseCommon Gotchas
`requests` inside `async def`
blocks the event loop. Use `httpx.AsyncClient` or a sync `def`.
Returning an ORM object without a `response_model`
you can leak columns. Be explicit.
Mutable module-level `ORDERS`
fine in an example, a race in production. Use a store with a lock or a database.
`HTTPException` is the control-flow return
a bare `return` of a dict is 200.