from slowapi import Limiter | |
from slowapi.util import get_remote_address | |
from slowapi.errors import RateLimitExceeded | |
from fastapi import FastAPI, Request | |
from starlette.responses import JSONResponse | |
# Initialize the limiter | |
limiter = Limiter(key_func=get_remote_address) | |
# Exception handler for rate limit exceeded | |
async def rate_limit_exceeded_handler(request: Request, exc: RateLimitExceeded): | |
return JSONResponse( | |
status_code=429, | |
content={"error": {"message": "Rate limit exceeded. Please wait and try again.", "type": "rate_limit"}} | |
) | |