Sobes.tech
Junior — Middle

What are the advantages of using middleware in FastAPI for request processing?

sobes.tech AI

Answer from AI

Middleware in FastAPI allows centralized processing of incoming requests and outgoing responses, which provides several advantages:

  • Code reuse: you can implement common logic (e.g., logging, authentication, CORS handling) in one place, without duplicating it in each endpoint.
  • Simplified architecture: separating cross-cutting concerns from business logic makes the code cleaner and more maintainable.
  • Flexibility: middleware can be easily added, removed, or reordered.

Example of simple middleware for logging request processing time:

from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def log_request_time(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    print(f"Request {request.url.path} took {process_time:.4f} seconds")
    return response