Junior — Middle
Have you used request rate limiting in FastAPI?
sobes.tech AI
Answer from AI
FastAPI does not have built-in rate limiting, but it can be implemented using third-party libraries such as slowapi or fastapi-limiter. This is useful for protecting the API from overload and preventing abuse.
Example using slowapi:
from fastapi import FastAPI, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from fastapi.responses import JSONResponse
app = FastAPI()
limiter = Limiter(key_func=get_remote_address)
app.state.limiter = limiter
@app.exception_handler(RateLimitExceeded)
async def rate_limit_handler(request: Request, exc: RateLimitExceeded):
return JSONResponse(status_code=429, content={"detail": "Too Many Requests"})
@app.get("/items")
@limiter.limit("5/minute")
async def read_items():
return {"message": "Hello, world!"}
This limit allows no more than 5 requests per minute from a single IP address.