Complete the code to import the correct module for timing.
from fastapi import FastAPI import [1] app = FastAPI()
The time module provides functions to measure time intervals, which is needed for timing requests.
Complete the code to define a middleware function that records the start time.
@app.middleware("http") async def add_process_time_header(request, call_next): start_time = [1]() response = await call_next(request) return response
time.time() returns the current time in seconds since the epoch, useful for measuring elapsed time.
Fix the error in calculating the process time by completing the blank.
@app.middleware("http") async def add_process_time_header(request, call_next): start_time = time.time() response = await call_next(request) process_time = time.time() [1] start_time response.headers["X-Process-Time"] = str(process_time) return response
To find the elapsed time, subtract the start time from the current time.
Fill both blanks to convert the process time to milliseconds and add it to the response headers.
@app.middleware("http") async def add_process_time_header(request, call_next): start_time = time.time() response = await call_next(request) process_time = (time.time() - start_time) [1] 1000 response.headers["X-Process-Time-ms"] = str(round(process_time, [2])) return response
Multiply seconds by 1000 to get milliseconds. Then round to 4 decimal places using round(process_time, 4).
Fill all three blanks to create a complete middleware that measures request time and adds it as a header rounded to 3 decimals.
from fastapi import FastAPI import time app = FastAPI() @app.middleware("http") async def add_process_time_header(request, call_next): start = [1]() response = await call_next(request) duration = [3]() - start response.headers["X-Process-Time"] = str(round(duration, [2])) return response @app.get("/") async def root(): return {"message": "Hello World"}
Use time.time() to get the start time, and round the duration to 3 decimals for readability.