Bird
0
0

You wrote this middleware but it does not run for any requests:

medium📝 Debug Q14 of 15
FastAPI - Middleware and Hooks
You wrote this middleware but it does not run for any requests:
class MyMiddleware:
    async def dispatch(self, request, call_next):
        print("Middleware active")
        response = await call_next(request)
        return response

app = FastAPI()
app.add_middleware(MyMiddleware)

What is the likely problem?
AMiddleware must be added after route definitions
Bdispatch method should be synchronous
CMyMiddleware does not inherit from BaseHTTPMiddleware
DMiddleware class must be decorated with @middleware
Step-by-Step Solution
Solution:
  1. Step 1: Check middleware class inheritance

    FastAPI middleware classes must inherit from BaseHTTPMiddleware or implement ASGI interface properly.
  2. Step 2: Identify missing inheritance

    MyMiddleware lacks inheritance, so FastAPI cannot use it as middleware.
  3. Final Answer:

    MyMiddleware does not inherit from BaseHTTPMiddleware -> Option C
  4. Quick Check:

    Middleware must inherit BaseHTTPMiddleware [OK]
Quick Trick: Middleware class must inherit BaseHTTPMiddleware [OK]
Common Mistakes:
MISTAKES
  • Making dispatch synchronous instead of async
  • Adding middleware before routes (order usually doesn't block)
  • Thinking @middleware decorator is required for class middleware

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes