Bird
0
0

How can you modify a custom middleware to conditionally block requests with a specific header value and return a 403 response immediately?

hard🚀 Application Q9 of 15
FastAPI - Middleware and Hooks
How can you modify a custom middleware to conditionally block requests with a specific header value and return a 403 response immediately?
AModify request object to remove header and then call call_next
BCheck header in dispatch; if blocked, return Response(status_code=403) without calling call_next
CCall call_next first, then check header and modify response status to 403
DRaise HTTPException(status_code=403) after calling call_next inside dispatch
Step-by-Step Solution
Solution:
  1. Step 1: Understand request blocking in middleware

    To block, middleware must return a response immediately without forwarding request.
  2. Step 2: Implement conditional check and return

    If header matches condition, return Response with 403 status code directly.
  3. Step 3: Confirm correct approach

    Check header in dispatch; if blocked, return Response(status_code=403) without calling call_next correctly returns Response early; Raise HTTPException(status_code=403) after calling call_next inside dispatch processes endpoint first then raises; Call call_next first, then check header and modify response status to 403 calls call_next first, too late; Modify request object to remove header and then call call_next modifies request but does not block.
  4. Final Answer:

    Check header in dispatch; if blocked, return Response(status_code=403) without calling call_next -> Option B
  5. Quick Check:

    Return Response early to block request [OK]
Quick Trick: Return Response early in dispatch to block requests [OK]
Common Mistakes:
MISTAKES
  • Calling call_next before blocking
  • Raising exceptions instead of returning Response
  • Modifying request but not blocking

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes