Custom Middleware, CORS & Global Exception Handlers
1Concept
Middleware intercepts every HTTP request and response cycle, allowing request timing, CORS headers (`CORSMiddleware`), request ID tagging, and centralized error logging.
2Architecture Diagram
Request ---> [ Custom Middleware: Timing ] ---> [ CORS Middleware ] ---> Route Handler ---> Response
3Code Example
Python 3.12
middleware_code = '''
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.perf_counter()
response = await call_next(request)
process_time = time.perf_counter() - start_time
response.headers["X-Process-Time"] = f"{process_time:.4f}s"
return response
'''
print("=== Custom HTTP Timing Middleware ===")
print(middleware_code.strip())4Expected Output
=== Custom HTTP Timing Middleware ===
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.perf_counter()
response = await call_next(request)
process_time = time.perf_counter() - start_time
response.headers["X-Process-Time"] = f"{process_time:.4f}s"
return response5Key Takeaways
- ✓Add CORS support via `from fastapi.middleware.cors import CORSMiddleware`.
- ✓Register custom exception handlers with `@app.exception_handler(CustomException)`.
- ✓Middleware runs in outer-to-inner order on requests and reverse order on responses.