Bird
0
0

Given this middleware in FastAPI:

medium📝 component behavior Q4 of 15
FastAPI - Middleware and Hooks
Given this middleware in FastAPI:
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()

class PrintMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        print("Before request")
        response = await call_next(request)
        print("After request")
        return response

app.add_middleware(PrintMiddleware)

@app.get("/hello")
async def hello():
    return {"msg": "Hello"}

What will be printed when a client requests GET /hello?
ABefore request After request
BAfter request Before request
COnly Before request
DOnly After request
Step-by-Step Solution
Solution:
  1. Step 1: Understand middleware dispatch flow

    Middleware prints "Before request", then calls next handler, then prints "After request".
  2. Step 2: Trace request through middleware and route

    When GET /hello is called, middleware prints before, route returns response, then middleware prints after.
  3. Final Answer:

    Before request After request -> Option A
  4. Quick Check:

    Middleware prints before and after call_next [OK]
Quick Trick: Middleware runs code before and after call_next(request) [OK]
Common Mistakes:
MISTAKES
  • Assuming prints happen only before or only after
  • Confusing order of prints
  • Thinking middleware skips printing after call_next

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes