Full answer
Middleware wraps the whole app; an APIRoute subclass wraps individual routes inside the router, with access to FastAPI-level data (the matched route, dependencies, response model).
Skeleton:
python
class GzipRequest(Request):
async def body(self) -> bytes:
if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("content-encoding"):
body = gzip.decompress(body)
self._body = body
return self._body
class GzipRoute(APIRoute):
def get_route_handler(self):
original = super().get_route_handler()
async def handler(request: Request) -> Response:
return await original(GzipRequest(request.scope, request.receive))
return handler
router = APIRouter(route_class=GzipRoute)Use cases:
- Decompressing request bodies (clients that gzip large JSON) or verifying signatures on the raw body before parsing.
- Logging request and response bodies (carefully) or timing per route, adding a header such as
X-Process-Time. - Custom exception translation for a router group, or tenant context set from the matched route.
- Caching the request body so multiple dependencies can read it.
Considerations:
- Overriding
body()on a Request subclass must keep working withrequest.json()and form parsing, since FastAPI reads the body through it. - Guard against decompression bombs: limit the decompressed size (
zlib.decompressobj().decompress(data, max_length)), and cap the compressed size. - The route class applies to routes created after it is set. Routes added through
include_routerkeep the class of their original router. - Keep route classes small. Middleware is simpler when you do not need route-level knowledge; dependencies are better for per-request inputs; a route class is the right tool when you must replace the Request or Response objects themselves.
python
import gzip
import json
from fastapi import APIRouter, FastAPI, Request, Response
from fastapi.routing import APIRoute
from fastapi.testclient import TestClient
from pydantic import BaseModel
from typing import Callable
MAX_DECOMPRESSED = 1_000_000
class GzipRequest(Request):
async def body(self) -> bytes:
if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("content-encoding"):
import zlib
d = zlib.decompressobj(16 + zlib.MAX_WBITS)
body = d.decompress(body, MAX_DECOMPRESSED) # cap the output size
if d.unconsumed_tail:
raise ValueError("decompressed body too large")
self._body = body
return self._body
class GzipRoute(APIRoute):
def get_route_handler(self) -> Callable:
original = super().get_route_handler()
async def handler(request: Request) -> Response:
response = await original(GzipRequest(request.scope, request.receive))
response.headers["X-Handled-By"] = "GzipRoute"
return response
return handler
app = FastAPI()
router = APIRouter(route_class=GzipRoute)
class Batch(BaseModel):
names: list[str]
@router.post("/batch")
async def batch(data: Batch):
return {"count": len(data.names)}
app.include_router(router)
@app.post("/plain")
async def plain(data: Batch):
return {"count": len(data.names)}
c = TestClient(app)
payload = json.dumps({"names": [f"S{i}" for i in range(1000)]}).encode()
compressed = gzip.compress(payload)
print(len(payload), "->", len(compressed), "bytes")
r = c.post("/batch", content=compressed, headers={"content-encoding": "gzip", "content-type": "application/json"})
print(r.status_code, r.json(), r.headers.get("x-handled-by"))
print(c.post("/batch", content=payload, headers={"content-type": "application/json"}).json())
r = c.post("/plain", content=compressed, headers={"content-encoding": "gzip", "content-type": "application/json"})
print("route without the custom class:", r.status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 7901 -> 2044 bytes 200 {'count': 1000} GzipRoute {'count': 1000} route without the custom class: 400
Key points
- Subclass APIRoute and wrap the handler in get_route_handler()
- Assign with APIRouter(route_class=...) to scope it to a router
- Use it to replace the Request or Response objects
- Guard against decompression bombs
- Prefer middleware or dependencies when route-level access is not needed
Common mistakes
- Using a route class where middleware or a dependency is enough
- Decompressing request bodies without a size cap
- Forgetting the route class applies per router, not globally
- Breaking request.json() by overriding body() incorrectly
Follow-ups
- How does a route class differ from middleware?
- How would you log request bodies safely?
- How do you apply a route class to all routers?
Tips
- Show get_route_handler
- Name two use cases
- Mention decompression limits