Script Valley
FastAPI: Build Production Python APIs
Authentication and SecurityLesson 4.5

How to add rate limiting and request size limits to FastAPI

slowapi, Limiter, rate limit decorator, IP-based limiting, custom key functions, request body size limit, middleware approach, 429 Too Many Requests

Rate Limiting in FastAPI

Rate limiting protects your API from abuse and prevents denial-of-service from runaway clients. The slowapi library brings Flask-Limiter's interface to FastAPI.

Install and configure

pip install slowapi
from fastapi import FastAPI, Request
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

Apply limits to routes

@app.get("/search")
@limiter.limit("10/minute")
async def search(request: Request, q: str):
    return {"q": q}

The request: Request parameter is required โ€” slowapi reads the client IP from it. Exceeding the limit returns a 429 with a Retry-After header automatically.

Request body size limit

from fastapi import Request
from fastapi.responses import JSONResponse

@app.middleware("http")
async def limit_body_size(request: Request, call_next):
    max_bytes = 1_000_000  # 1 MB
    if int(request.headers.get("content-length", 0)) > max_bytes:
        return JSONResponse({"error": "Payload too large"}, status_code=413)
    return await call_next(request)

This middleware pattern is reusable and runs before any route logic, preventing large uploads from consuming memory.

How to add rate limiting and request size limits to FastAPI โ€” Authentication and Security โ€” FastAPI: Build Production Python APIs โ€” Script Valley โ€” Script Valley