FastAPI Tutorial
Learn how to integrate rate limiting in your FastAPI application.
Halt provides a dedicated `HaltMiddleware` for FastAPI that integrates seamlessly with dependency injection and background tasks.
1. Installation
pip install halt[fastapi]2. Basic Setup
Add the middleware to your FastAPI application.
from fastapi import FastAPI
from halt import RateLimiter, InMemoryStore, presets
from halt.adapters.fastapi import HaltMiddleware
app = FastAPI()
# Create a limiter
limiter = RateLimiter(
store=InMemoryStore(),
policy=presets.PUBLIC_API
)
# Add middleware
app.add_middleware(HaltMiddleware, limiter=limiter)3. Customizing Limits per Route
You can override limits for specific routes using dependencies or by creating separate limiters. Currently, the middleware applies globally. To apply per-route, you can use dependencies.
from fastapi import Depends
async def rate_limit(request: Request):
# Custom logic
pass
@app.get("/expensive", dependencies=[Depends(rate_limit)])
async def expensive_op():
return {"status": "ok"}*Note: Full per-route decorator support is coming in v0.2.0.*