SlowAPI is a Python library that provides a flexible rate-limiting extension for Starlette and FastAPI applications. It builds upon the 'limits' library to offer various storage backends (in-memory, Redis, Memcached) and granular control over rate limits per route or globally. The current version is 0.1.9, and it is actively maintained with an irregular release cadence.
pip install slowapiVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate SlowAPI with a FastAPI application. It sets up a global `Limiter` instance using the client's IP address (`get_ipaddr`) for identification and registers an exception handler for `RateLimitExceeded` errors. Two endpoints are defined, one with a 10 requests/minute limit and another with a 2 requests/second limit, showcasing both global and route-specific rate limiting.
Place `app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)` and ensure `app.state.limiter` is set *before* other middlewares if using the middleware approach, or be mindful of the order in `app.add_middleware()`.
Always provide a `key_func` during `Limiter` initialization. For custom identification (e.g., by user ID), define a function that extracts the ID from the `Request` object (e.g., `request.state.user.id`).
Add `app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)` to your FastAPI/Starlette application setup.
Ensure `storage_uri` is correctly set, e.g., `memory://` for testing, `redis://localhost:6379` for Redis, or `memcached://localhost:11211` for Memcached. Install the necessary optional dependencies (e.g., `slowapi[redis]`) for non-memory backends.