Bird
0
0

You implemented this middleware class:

medium📝 Debug Q6 of 15
FastAPI - Middleware and Hooks
You implemented this middleware class:
class MyMiddleware:
    async def dispatch(self, request, call_next):
        print("Running")
        response = await call_next(request)
        return response

app = FastAPI()
app.add_middleware(MyMiddleware)

Why does this middleware never execute when requests are made?
ABecause dispatch method is missing the self parameter
BBecause MyMiddleware does not inherit from a proper middleware base class
CBecause add_middleware requires a function, not a class
DBecause the middleware is added after the app starts
Step-by-Step Solution
Solution:
  1. Step 1: Check middleware class inheritance

    FastAPI middleware classes must inherit from Starlette's BaseHTTPMiddleware or similar.
  2. Step 2: Identify missing inheritance

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

    Because MyMiddleware does not inherit from a proper middleware base class -> Option B
  4. Quick Check:

    Middleware must inherit BaseHTTPMiddleware or similar [OK]
Quick Trick: Middleware classes must inherit BaseHTTPMiddleware [OK]
Common Mistakes:
MISTAKES
  • Not inheriting from BaseHTTPMiddleware
  • Incorrect method signatures
  • Adding middleware after app startup

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes