Middleware

I deliberated a lot about including the following sections at the start or end of the documentation. But, in the end, I’ve opted for the beginning under the banner of “Optional”. It will be a personal preference or depend on what you are building. For example, you may avoid touching certificates until the final public deployment. However, you can use self-signed certificates for internal applications or learn in a local development environment.

Middleware#

There may be many examples of middleware in FastAPI. This section introduces a simple yet helpful example that will include a response time in the header of every request to any of your APIs added to the project. Add the following to your main.py, requiring time and Request imports.

main.pypython
import time  # NEW

import uvicorn
from fastapi import FastAPI, Request  # NEW
from api import health_api
from config.settings import settings

main_app = FastAPI()

# Middleware                                                     # NEW
@main_app.middleware("http")                                     # NEW
async def add_process_time_header(request: Request, call_next):  # NEW
    start_time = time.perf_counter()                             # NEW
    response = await call_next(request)                          # NEW
    process_time = time.perf_counter() - start_time              # NEW
    response.headers["X-Process-Time"] = str(process_time)       # NEW
    return response                                              # NEW

def configure():
    configure_routing()

def configure_routing():
    main_app.include_router(health_api.router, prefix=settings.CONF_API_V1_STR, tags=["health"])

if __name__ == '__main__':
    configure()
    uvicorn.run(main_app,
                host=settings.CONF_MAIN_APP_HOST,
                port=settings.CONF_MAIN_APP_PORT)
else:
    configure()

time.perf_counter() is used rather than time.time() because it’s a monotonic, high-resolution clock intended for measuring durations.

Now, responses will include x-process-time, for example:

curl 'http://127.0.0.1:8000/api/v1/health' -H 'accept: application/json' -v

Example output:

> GET /api/v1/health HTTP/1.1
> Host: 127.0.0.1:8000
> accept: application/json
>
< HTTP/1.1 200 OK
< server: uvicorn
< content-length: 15
< content-type: application/json
< x-health-check: ok
< x-process-time: 0.0009006580003187992
<
{"health":"ok"}