A. Middleware must be added after route definitions
B. dispatch method should be synchronous
C. MyMiddleware does not inherit from BaseHTTPMiddleware
D. Middleware class must be decorated with @middleware
Solution
Step 1: Check middleware class inheritance
FastAPI middleware classes must inherit from BaseHTTPMiddleware or implement ASGI interface properly.
Step 2: Identify missing inheritance
MyMiddleware lacks inheritance, so FastAPI cannot use it as middleware.
Final Answer:
MyMiddleware does not inherit from BaseHTTPMiddleware -> Option C
Quick Check:
Middleware must inherit BaseHTTPMiddleware [OK]
Hint: Middleware class must inherit BaseHTTPMiddleware [OK]
Common Mistakes:
Making dispatch synchronous instead of async
Adding middleware before routes (order usually doesn't block)
Thinking @middleware decorator is required for class middleware
5. You want to add middleware that logs request time but only for routes under /api. Why does FastAPI middleware still run on all routes, and how can you limit it?
hard
A. FastAPI does not support middleware; use dependencies instead
B. Middleware can be added only to specific routes by passing route list to add_middleware
C. Middleware runs globally but can be disabled per route with a decorator
D. Middleware runs globally by design; to limit, check path inside middleware and skip non-/api requests
Solution
Step 1: Understand middleware scope
FastAPI middleware always runs globally on every request to handle shared tasks.
Step 2: Limit middleware effect by path check
To restrict middleware to /api routes, check the request URL path inside middleware and skip processing for others.
Final Answer:
Middleware runs globally by design; to limit, check path inside middleware and skip non-/api requests -> Option D