Trung BìnhFastAPI iconFastAPI

Middleware trong FastAPI dùng khi nào?

Middleware bọc toàn bộ request/response, phù hợp cho cross-cutting concern như request id, logging, timing, CORS, compression, trusted host hoặc security headers.

Ví dụ timing middleware:

python
@app.middleware("http")
async def add_process_time(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    response.headers["X-Process-Time"] = str(time.perf_counter() - start)
    return response

Không nên nhét business logic vào middleware vì nó thiếu context của route handler và khó test theo domain.

Xem toàn bộ FastAPI cùng filter theo level & chủ đề con.

Mở danh sách FastAPI