Middleware ใน FastAPI คือโค้ดที่ทำงานสำหรับ ทุก request และ response — ห่อหุ้ม endpoints ของคุณเพื่อจัดการกับเรื่องที่ตัดข้ามกัน (cross-cutting concerns) เช่น logging, การจับเวลา, CORS และการเพิ่ม headers FastAPI ใช้ระบบ middleware ของ Starlette (มันเป็น ASGI-based)
การเขียน custom middleware
time
():
start = time.time()
response = call_next(request)
response.headers[] = (time.time() - start)
response
