FastAPI Limiter

0.2.0 · active · verified Tue Apr 14

fastapi-limiter is a Python library that provides robust request rate limiting capabilities for FastAPI applications. It integrates with Redis as a backend to store and manage rate limit counters. Currently at version 0.2.0, it's an early-stage project with releases driven by feature additions and bug fixes, and primarily supports Python 3.9 and above.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `fastapi-limiter` with an async Redis client during FastAPI's application startup event. It then applies different rate limits to two distinct endpoints using the `RateLimiter` dependency. The Redis connection uses an environment variable for configuration.

import os
from fastapi import FastAPI, Depends
from fastapi_limiter import FastAPILimiter
from fastapi_limiter.depends import RateLimiter
from redis.asyncio import Redis # Use asyncio for FastAPI

app = FastAPI()

# Configure Redis URL via environment variable or default to localhost
REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379')

@app.on_event('startup')
async def startup():
    redis_client = Redis.from_url(REDIS_URL, encoding='utf8', decode_responses=True)
    await FastAPILimiter.init(redis_client)
    print("FastAPILimiter initialized.")

@app.get('/', dependencies=[Depends(RateLimiter(times=2, seconds=5))])
async def homepage():
    return {'message': 'Hello world!'}

@app.get('/limited', dependencies=[Depends(RateLimiter(times=1, seconds=10))])
async def limited_endpoint():
    return {'message': 'This endpoint is more limited!'}

# To run this example:
# 1. Install uvicorn: pip install uvicorn
# 2. Run Redis locally (e.g., via Docker: docker run --name some-redis -p 6379:6379 -d redis)
# 3. Save the code as main.py
# 4. Execute: uvicorn main:app --reload

view raw JSON →