Bird
0
0

Identify the error in this FastAPI request timing middleware code:

medium📝 Debug Q14 of 15
FastAPI - Middleware and Hooks
Identify the error in this FastAPI request timing middleware code:
import time
from fastapi import FastAPI
app = FastAPI()

@app.middleware('http')
def timing_middleware(request, call_next):
    start = time.time()
    response = call_next(request)
    duration = time.time() - start
    response.headers['X-Time'] = str(duration)
    return response
AMissing async keyword and missing await before call_next(request)
BUsing time.time() instead of datetime.now()
CResponse headers cannot be modified in middleware
DMiddleware should be defined with @app.route decorator
Step-by-Step Solution
Solution:
  1. Step 1: Check function signature and async usage

    Middleware must be async and await call_next(request) because call_next is async.
  2. Step 2: Identify missing await and async

    Code lacks async def and await, causing runtime errors.
  3. Final Answer:

    Missing async keyword and missing await before call_next(request) -> Option A
  4. Quick Check:

    Async + await call_next required [OK]
Quick Trick: Middleware must be async and await call_next(request) [OK]
Common Mistakes:
MISTAKES
  • Forgetting async keyword on middleware function
  • Not awaiting call_next(request)
  • Using wrong decorator like @app.route

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes