SlowAPI: Rate Limiting for Starlette & FastAPI

0.1.9 · active · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

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.

import uvicorn
from fastapi import FastAPI, Request
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_ipaddr
from slowapi.errors import RateLimitExceeded

# Initialize Limiter with a key function and default limits
# Using in-memory storage for simplicity, but can be 'redis://localhost:6379' etc.
limiter = Limiter(key_func=get_ipaddr, default_limits=["5/minute", "100/day"])
app = FastAPI()
app.state.limiter = limiter # Essential for decorator-based limits

# Register the exception handler to return a 429 response
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get("/unlimited")
async def read_unlimited():
    return {"message": "This endpoint is not rate limited."}

@app.get("/")
@limiter.limit("10/minute") # Route-specific limit
async def read_root(request: Request):
    # The 'request' argument is required by the key_func (get_ipaddr)
    return {"message": "Hello, rate-limited world!"}

@app.get("/fast/")
@limiter.limit("2/second", "/fast/") # Another route with a custom scope
async def read_fast(request: Request):
    return {"message": "Too fast, too furious!"}

# To run this application:
# 1. Save the code as 'main.py'
# 2. Run from your terminal: uvicorn main:app --reload --port 8000

view raw JSON →