SlowAPI is a Python library specifically designed to add rate limiting to FastAPI and Starlette applications. It is heavily inspired by (and based on) flask-limiter, adapting its battle-tested logic for the modern, asynchronous nature of FastAPI.
Its primary job is to prevent your API from being overwhelmed by too many requests—whether from a single user, a bot, or a malicious actor—by restricting how many times an endpoint can be called within a specific timeframe (e.g., "5 requests per minute").
Key Features
* Decorator Support: Apply limits to specific routes using @limiter.limit().
* Global Limits: Apply a default limit to every route in your application.
* Flexible Identification: Rate limit based on IP address, headers, or even custom authentication tokens.
* Storage Backends: Supports in-memory tracking (default), Redis, or Memcached for distributed systems.
Basic Example: FastAPI + SlowAPI
To use SlowAPI, you first need to install it:
pip install slowapi
Below is a complete implementation that limits a specific endpoint to 5 requests per minute per IP address.
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
# 1. Initialize the Limiter
# 'key_func' determines how to identify the user (here, by their IP address)
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
# 2. Attach the limiter to the app state
app.state.limiter = limiter
# 3. Add the exception handler to return a 429 error when limits are hit
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
@app.get("/ping")
# 4. Apply the limit to a specific route
@limiter.limit("5/minute")
async def ping(request: Request):
return {"message": "pong"}
@app.get("/unlimited")
async def unlimited(request: Request):
return {"message": "I have no limits!"}
Important Usage Notes:
* The Request object: Every route you want to rate limit must explicitly accept the request: Request argument, even if you don't use it in your code. SlowAPI needs this object to extract the client's identity (like the IP).
* Order of Decorators: If you are using other decorators (like @app.get), ensure the @limiter.limit decorator is placed below the FastAPI route decorator.
Comparison: Rate Limiting Strategies
| Strategy | Description | Best For |
|---|---|---|
| Fixed Window | Resets at the start of every minute/hour. | Simple, predictable apps. |
| Sliding Window | Calculates usage over a rolling time window. | High-precision accuracy. |
| Token Bucket | Allows "bursts" of requests while maintaining an average rate. | APIs that expect occasional spikes. |
Would you like me to show you how to set up Global Rate Limits so you don't have to add a decorator to every single route?
Quick and Easy Rate Limiting for FastAPI
This video provides a practical walkthrough of setting up SlowAPI in a FastAPI project, including different strategies for managing traffic.
YouTube video views will be stored in your YouTube History, and your data will be stored and used by YouTube according to its Terms of Service
No comments:
Post a Comment