0
0
FastAPIframework~5 mins

Request timing middleware in FastAPI

Choose your learning style9 modes available
Introduction

Request timing middleware helps you know how long each web request takes. This is useful to find slow parts and improve your app.

You want to measure how fast your API responds to users.
You need to find slow requests to fix performance issues.
You want to log request times for monitoring or debugging.
You want to show request duration in response headers for clients.
You want to learn how middleware works in FastAPI.
Syntax
FastAPI
from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def timing_middleware(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    duration = time.time() - start_time
    response.headers["X-Process-Time"] = str(duration)
    return response

The middleware function uses @app.middleware("http") decorator.

call_next(request) calls the next handler and returns the response.

Examples
This example adds a header showing how long the request took.
FastAPI
from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    process_time = time.time() - start
    response.headers["X-Process-Time"] = str(process_time)
    return response
This example prints the request duration to the console for each request.
FastAPI
from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def log_request_time(request: Request, call_next):
    start = time.time()
    response = await call_next(request)
    duration = time.time() - start
    print(f"Request to {request.url.path} took {duration:.4f} seconds")
    return response
Sample Program

This FastAPI app has middleware that measures how long each request takes. It adds the time in seconds as a header called X-Process-Time. The root endpoint returns a simple greeting.

FastAPI
from fastapi import FastAPI, Request
import time

app = FastAPI()

@app.middleware("http")
async def timing_middleware(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    duration = time.time() - start_time
    response.headers["X-Process-Time"] = str(duration)
    return response

@app.get("/")
async def read_root():
    return {"message": "Hello, world!"}
OutputSuccess
Important Notes

Middleware runs for every request before and after the main handler.

Use time.time() to get current time in seconds.

Adding timing info in headers helps clients see performance without changing response body.

Summary

Request timing middleware measures how long each request takes.

It uses @app.middleware("http") and call_next(request).

Timing info can be added to response headers or logged for monitoring.