FastAPI’s elegant architecture makes it easy to build robust APIs, but as your applications grow, you’ll inevitably face the challenge of managing cross-cutting concerns like logging, request modification, security, and more. This is where FastAPI’s middleware system shines.
In this article, I’ll walk you through the essentials of using middleware in FastAPI, including practical use cases, implementation basics, and some tips for best practices.
What is Middleware in FastAPI?
Middleware is a function that gets called for every request before (and after) it reaches your endpoint logic. It’s ideal for handling concerns that shouldn’t pollute your business logic, such as:
- Request/response logging
- CORS handling
- Authentication
- Response compression or modification
- Rate limiting (see my prior article for more)
Creating Custom Middleware
Let’s look at a simple example: logging incoming requests and outgoing responses.
from fastapi import FastAPI, Request
import time
app = FastAPI()
@app.middleware("http")
async def log_requests(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
duration = time.time() - start_time
print(f"{request.method} {request.url.path} completed in {duration:.4f}s")
return response
This tiny bit of code gives you insight into request duration and processing.
Using Starlette Middleware
FastAPI runs on Starlette, so you can directly use a wide range of Starlette middleware. For example, adding GZip support:
from starlette.middleware.gzip import GZipMiddleware
app.add_middleware(GZipMiddleware, minimum_size=1000)
Or CORS support:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
Middleware: Best Practices
- Order Matters: Middlewares are applied in the order they are added. Be mindful of interactions.
- Error Handling: If your middleware can raise exceptions, ensure they’re handled gracefully (see my earlier article on exception handling).
- Keep it Fast: Middleware runs for every request, so strive for efficiency.
Conclusion
Middleware lets you handle recurring concerns at the framework level, keeping your endpoint code clean and DRY. Think of it as a powerful tool in your FastAPI toolkit to manage evolving application needs.
Stay tuned for more FastAPI tips and, as always, happy coding! — Fast Eddy
Leave a Reply