Web APIs with FastAPI
FastAPI builds an API from normal Python functions and type hints. Pydantic v2 models check every request and shape every response. Dependencies give each request what it needs, like its own database session, and close it at the end. The most important senior detail is the difference between async def and def endpoints. One blocking call in an async def endpoint slows down every request on that worker.
Author: bezzad
Contents
The problem: an API that trusts everything
The first version of our shop API had three problems:
- It took the request body as a plain dict. A client sent a quantity of -5, and the order total became negative.
- It returned the database row as it was. The answer also had the cost_price field, so every customer could see our buying price.
- It used one global database session for all requests. Under load, two requests used the same session at the same time and got strange errors.
FastAPI and Pydantic fix all three, if you use them the right way.
Path operations
A path operation is a function plus an HTTP method and a path. FastAPI reads the type hints of the parameters:
from fastapi import FastAPI
app = FastAPI()
@app.get("/products/{product_id}")
def get_product(product_id: int):
return {"id": product_id}
@app.get("/products")
def list_products(limit: int = 20, offset: int = 0):
return {"limit": limit, "offset": offset}
- A parameter whose name is in the path (product_id) is a path parameter. Because of the int hint, the text “abc” is rejected with status 422.
- Other simple parameters (limit, offset) are query parameters. A default value makes them optional.
- A parameter whose type is a Pydantic model is read from the JSON body.
- FastAPI also builds OpenAPI docs from the same hints. By default, they are on the page named docs of your app.
Request models: validation with Pydantic v2
A Pydantic model describes what valid input looks like. FastAPI checks every request against it before your function runs.
from pydantic import BaseModel, Field, field_validator
class OrderLine(BaseModel):
product_id: int
quantity: int = Field(gt=0, le=100)
class OrderIn(BaseModel):
lines: list[OrderLine] = Field(min_length=1)
coupon: str | None = None
@field_validator("coupon")
@classmethod
def normalize_coupon(cls, value: str | None) -> str | None:
return value.strip().upper() if value else None
- A quantity of 0 or -5 is rejected with status 422, and the answer says which field is wrong and why.
- An empty list of lines is rejected too, because of the min_length rule.
- A field validator can check or clean a value. Here the coupon is trimmed and made uppercase.
- Your function gets a real OrderIn object, not a dict. Your editor and type checker know every field.
Pydantic v2 renamed some methods from v1. Use model_validate instead of parse_obj, model_dump instead of dict, and the model_config setting instead of an inner Config class.
Response models: send only what you mean to send
The response model is the second half of the contract. It decides what leaves your API.
from decimal import Decimal
from pydantic import ConfigDict
class ProductOut(BaseModel):
# read from ORM objects
model_config = ConfigDict(from_attributes=True)
id: int
name: str
price: Decimal
@app.get("/products/{product_id}", response_model=ProductOut)
def get_product(product_id: int, db: DbSession):
product = db.get(Product, product_id)
if product is None:
raise HTTPException(404, detail="Product not found")
return product # FastAPI keeps only the fields of ProductOut
- The database row has cost_price, but ProductOut does not. FastAPI drops every field that is not in the response model.
- The from_attributes setting lets Pydantic read the fields from an object (like a SQLAlchemy row), not only from a dict.
- Keep input and output models separate. OrderIn has no id and no status, because the client must not set them. OrderOut has them.
- Pydantic v2 writes Decimal values as strings in JSON, like “80.00”. This keeps the exact value. Tell your API clients.
Dependencies
A dependency is a function that FastAPI calls before your endpoint, and whose result it passes in. Use the Depends marker inside Annotated:
from collections.abc import Iterator
from typing import Annotated
from fastapi import Depends, HTTPException
from sqlalchemy import create_engine
from sqlalchemy.orm import Session, sessionmaker
engine = create_engine(
"postgresql+psycopg://shop@db/shop",
pool_pre_ping=True,
)
SessionLocal = sessionmaker(engine, expire_on_commit=False)
def get_db() -> Iterator[Session]:
with SessionLocal() as session: # one session for one request
yield session # the endpoint runs here
# the with block closes the session after the request
DbSession = Annotated[Session, Depends(get_db)]
- A dependency with yield works in two parts. The code before yield runs before the endpoint. The code after yield (here, the end of the with block) runs after the request is done.
- Each request gets its own session. FastAPI calls get_db once for each request.
- The DbSession alias keeps endpoints short. Any endpoint that has a parameter of this type gets a session.
- Dependencies can depend on other dependencies. For example, a current_user dependency can use the session and the auth token.
- In tests, you can replace a dependency with the dependency_overrides dict of the app. For example, a test session instead of the real one.
One session per request, never a global one
Why not one global session for the whole app?
- A SQLAlchemy Session is not thread-safe. Normal def endpoints run in a thread pool, so two requests may use one global session at the same time.
- A session holds a transaction and a unit of work. One request’s changes and errors leak into the next request.
- After one failed query, the session needs a rollback. With a global session, one bad request breaks all the next ones.
The engine is different. It is made once, at startup, and it holds the connection pool. Many sessions share it safely.
async def or def?
This is the most important senior question about FastAPI. FastAPI treats the two kinds differently:
- An async def endpoint runs on the event loop, in the main thread of the worker. It must never block.
- A def endpoint runs in a thread pool. FastAPI waits for it without blocking the event loop. Blocking calls are fine there.
- The same rule holds for dependencies: a def dependency also runs in the thread pool.
import time
import requests
import httpx
@app.get("/shipping/bad")
async def shipping_bad():
# blocks the event loop
time.sleep(1)
# requests also blocks the event loop
return requests.get("https://carrier.example/price").json()
@app.get("/shipping/ok-sync")
def shipping_ok_sync():
# runs in a thread, so blocking is fine here
url = "https://carrier.example/price"
return requests.get(url, timeout=5).json()
@app.get("/shipping/ok-async")
async def shipping_ok_async():
async with httpx.AsyncClient(timeout=5) as client:
response = await client.get("https://carrier.example/price")
return response.json()
- In shipping_bad, while one request waits one second, the worker cannot answer any other request.
- The sync version is fine, because it runs in a thread. But the thread pool has a limit. Very many slow calls at once will wait for a free thread.
- The async version is the best choice when every library inside is async.
- The rule of thumb: if you use a sync library (like a sync database session), write def. Write async def only when everything you await inside is async.
Errors and status codes
- Raise HTTPException for a known problem, with a status and a message. For example, 404 when the product does not exist.
- Set the status of success in the decorator. A create endpoint should return 201, with the status_code option.
- Do not return error details from inside your code (stack traces, SQL). Log them, and send a short message.
from fastapi import status
@app.post(
"/orders",
response_model=OrderOut,
status_code=status.HTTP_201_CREATED,
)
def create_order(order: OrderIn, db: DbSession):
...
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| A dict as the request body | Bad data reaches the database. | A Pydantic model with rules like gt and min_length. |
| Returning the ORM object with no response model | Internal fields like cost_price leak. | A separate output model. |
| One global database session | Errors under load, and one bad request breaks others. | A dependency with yield: one session per request. |
| A blocking library inside async def | Every request on the worker waits. | A def endpoint, or async libraries. |
| async def with a sync database session | Same as above, but harder to see. | Write def, or use an async session. |
| No timeout on outgoing HTTP calls | Threads or tasks that hang forever. | A timeout on every client. |
| Pydantic v1 methods like dict and parse_obj | Deprecation warnings, and code that breaks later. | model_dump and model_validate. |
Summary in 7 lines
- FastAPI reads type hints to find path, query and body parameters, and to build the docs.
- Request models validate every input before your code runs. Bad input gets status 422.
- Response models decide what leaves the API. Keep input and output models separate.
- A dependency with yield prepares something before the endpoint and cleans it up after the request.
- Give each request its own database session. Share only the engine.
- An async def endpoint runs on the event loop and must never block. A def endpoint runs in a thread pool.
- Use HTTPException and the right status codes, and never leak internal details.