In FastAPI (and its underlying framework Starlette), middlewares are executed in the order they are added to the application.
Think of it like layers of an onion or nested functions:
- Request Incoming: The request first hits the middleware that was added first.
- Passing Down: That middleware processes the request and then passes it to the
next_app (which is the next middleware in the stack, or the actual FastAPI endpoint if it's the last middleware).
- Stack Execution: This continues down the stack. The middleware added last will be the one closest to your actual FastAPI route handler.
- Endpoint Execution: Finally, the request reaches your path operation function (your route handler).
- Response Outgoing: The response from your path operation function travels back up the stack. The middleware that received the request last (the one added last) will process the response first on its way out.
- Final Response: The response eventually exits through the middleware that was added first.
In summary:
- Request Flow: Middleware 1 -> Middleware 2 -> ... -> Middleware N -> FastAPI Endpoint
- Response Flow: FastAPI Endpoint -> Middleware N -> ... -> Middleware 2 -> Middleware 1
How to add middleware:
You typically add middleware using the app.add_middleware() method:
from fastapi import FastAPI
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import Response
import time
# Example Middleware 1
class Middleware1(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
start_time = time.time()
print(f"Middleware1: Processing request ({request.method} {request.url.path})")
# Process request and pass to the next middleware/endpoint
response = await call_next(request)
process_time = time.time() - start_time
print(f"Middleware1: Sending response ({response.status_code}) - Process time: {process_time:.4f}s")
# You can modify the response here if needed
response.headers["X-Middleware1-Processed"] = "true"
return response
# Example Middleware 2
class Middleware2(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
print(f"Middleware2: Processing request ({request.method} {request.url.path})")
# Process request and pass to the next middleware/endpoint
response = await call_next(request)
print(f"Middleware2: Received response ({response.status_code})")
# You can modify the response here if needed
response.headers["X-Middleware2-Processed"] = "true"
return response
app = FastAPI()
# Add Middleware 1 FIRST
app.add_middleware(Middleware1)
# Add Middleware 2 SECOND
app.add_middleware(Middleware2)
@app.get("/")
async def read_root():
print("Endpoint: Handling request for /")
return {"message": "Hello World"}
# To run this example:
# 1. Save as main.py
# 2. Run: uvicorn main:app --reload
# 3. Access http://127.0.0.1:8000/ in your browser or using curl
Expected Output (when accessing /):
Middleware1: Processing request (GET /) # Middleware 1 receives request first
Middleware2: Processing request (GET /) # Middleware 2 receives request second
Endpoint: Handling request for / # Endpoint receives request last
Middleware2: Received response (200) # Middleware 2 sees response first on the way out
Middleware1: Sending response (200) - Process time: 0.000Xs # Middleware 1 sees response last on the way out
Notice how the "Processing request" logs appear in the order the middleware were added, and the "Received response" / "Sending response" logs appear in the reverse order.