Middle
What is Middleware in FastAPI and why is it needed?
sobes.tech AI
Answer from AI
Middleware in FastAPI is a component that intercepts HTTP requests and responses at the application level, allowing for additional processing before and after calling endpoints.
Why is Middleware needed:
- Logging requests and responses
- Error and exception handling
- Managing CORS
- Authentication and authorization
- Modifying or adding headers
Example of simple middleware that outputs the request processing time:
from fastapi import FastAPI, Request
import time
app = FastAPI()
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response