FastAPI Middleware
Middleware is a function that runs before and after each request reaches the route handler.
Middleware can be used to add logging, modify requests/responses, handle CORS, and other common logic.
How middleware works
The execution flow of middleware:
- Request arrives at the middleware
- Middleware runs pre-processing logic
- Middleware passes the request to the next middleware or route function
- Route function returns a response
- Middleware runs post-processing logic
- Response is returned to the client

| Name | Purpose |
|---|---|
| Client | Browsers, front-end apps, Postman, etc., send HTTP requests to FastAPI |
| Request | HTTP request object, containing data such as URL, headers, body, and cookies |
| Middleware 1 | The first layer of processing after the request enters |
| Middleware 2 | Second layer of processing logic |
| Middleware N | Multiple middleware execute in order |
| Route handler (Path Operation) | Where the business code actually runs |
| Response phase | After the route returns a Response, the response passes through the middleware again |
| Middleware returns in reverse order | The response returns in "reverse order" |
| Response | The data finally returned to the client |
Creating middleware
Use @app.middleware("http") decorator to create middleware:
Example
import
time
from
fastapi
import
FastAPI
,
Request
app
=
FastAPI
(
)
@
app.
middleware
(
"http"
)
async
def
add_process_time_header
(
request: Request
,
call_next
)
:
1. Pre-request processing: record the start time
start_time
=
time
.
time
(
)
2. Pass the request to the next middleware or route function
response
=
await call_next
(
request
)
3. Post-response processing: calculate the processing time and add a response header
process_time
=
time
.
time
(
)
- start_time
response.
headers
[
"X-Process-Time"
]
=
str
(
process_time
)
return
response
@
app.
get
(
"/"
)
async
def
root
(
)
:
return
{
"message"
:
"Hello World"
}
Code explanation:
| Section | Description |
|---|---|
@app.middleware("http") |
Declare that this is an HTTP middleware |
request: Request |
The current request object |
call_next |
The callback that invokes the next middleware or route function |
await call_next(request) |
Pass the request to the next layer and get the response |
call_nextreceiverequestparameter and returns aresponse. You can modify the request before callingcall_nextand modify the response after the call.
Request logging middleware
The following middleware logs basic information about each request:
Example
import
time
import
logging
from
fastapi
import
FastAPI
,
Request
app
=
FastAPI
(
)
logger
=
logging
.
getLogger
(
"uvicorn.access"
)
@
app.
middleware
(
"http"
)
async
def
log_requests
(
request: Request
,
call_next
)
:
Log request information
logger.
info
(
f
"Request: {request.method} {request.url}"
)
start_time
=
time
.
time
(
)
response
=
await call_next
(
request
)
process_time
=
time
.
time
(
)
- start_time
Log response information
logger.
info
(
f
"Response: {request.method} {request.url} "
f
"status_code={response.status_code} elapsed={process_time:.3f}s"
)
return
response
Middleware execution order
Middleware executes in registration order: requests pass through middleware in forward order, responses pass through in reverse order:
请求 -> 中间件A(前) -> 中间件B(前) -> 路由函数
响应 <- 中间件A(后) <- 中间件B(后) <- 路由函数
The registration order of middleware matters. If you have two middleware A and B, registering A first means the request passes through A then B, but the response passes through B then A.
Using Starlette's built-in middleware
FastAPI inherits from Starlette, so you can directly use the middleware provided by Starlette:
Example
from
fastapi
import
FastAPI
from
starlette.
middleware
.
httpsredirect
import
HTTPSRedirectMiddleware
app
=
FastAPI
(
)
Force HTTPS redirect
app.
add_middleware
(
HTTPSRedirectMiddleware
)
@
app.
get
(
"/"
)
async
def
root
(
)
:
return
{
"message"
:
"Use HTTPS"
}
Commonly used built-in middleware:
| Middleware | Description |
|---|---|
HTTPSRedirectMiddleware |
Force HTTP requests to redirect to HTTPS |
TrustedHostMiddleware |
Restrict the allowed hostnames |
GZipMiddleware |
Automatically compress response content |
CORSMiddleware |
Handle cross-origin requests (detailed in the next chapter) |
GZip compression middleware
Enabling GZip compression can reduce response size and improve transfer speed:
Example
from
fastapi
import
FastAPI
from
fastapi.
middleware
.
gzip
import
GZipMiddleware
app
=
FastAPI
(
)
Automatically compress when the response size exceeds 1000 bytes
app.
add_middleware
(
GZipMiddleware
,
minimum_size
=
1000
)
@
app.
get
(
"/"
)
async
def
root
(
)
:
return
{
"message"
:
"This response may be GZip compressed"
}
Summary
- Middleware runs common logic in the request/response processing chain
- Use
@app.middleware("http")Creating custom middleware call_next(request)Pass the request to the next layer- Middleware executes in registration order (requests in forward order, responses in reverse)
- FastAPI/Starlette provides built-in middleware such as CORS, GZip, and HTTPS redirect