Bird
0
0

Given this middleware code, what will be the response header 'X-Custom' value?

medium📝 component behavior Q4 of 15
FastAPI - Middleware and Hooks
Given this middleware code, what will be the response header 'X-Custom' value?
from starlette.middleware.base import BaseHTTPMiddleware

class CustomHeaderMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request, call_next):
        response = await call_next(request)
        response.headers['X-Custom'] = 'Hello'
        return response

app.add_middleware(CustomHeaderMiddleware)
ANo 'X-Custom' header added
B'Hello'
CRaises an error because headers are immutable
D'CustomHeaderMiddleware'
Step-by-Step Solution
Solution:
  1. Step 1: Analyze dispatch method behavior

    The middleware waits for the response from the next handler, then adds a header 'X-Custom' with value 'Hello'.
  2. Step 2: Confirm header modification

    Response headers are mutable; adding 'X-Custom' with 'Hello' succeeds.
  3. Final Answer:

    'Hello' -> Option B
  4. Quick Check:

    Response header 'X-Custom' = 'Hello' [OK]
Quick Trick: Modify response headers after call_next(request) [OK]
Common Mistakes:
MISTAKES
  • Assuming headers are immutable and cause error
  • Forgetting to await call_next
  • Expecting middleware class name as header value

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes