fapi-limiter
Flexible rate limiting for FastAPI powered by pyrate-limiter.
This project is being developed with AI assistance (GitHub Copilot), but all code, design decisions, and implementation details are reviewed and validated by the author.
Installation
# pip
pip install fapi-limiter
# uv
uv add fapi-limiter
Usage
Middleware (app-wide)
Apply rate limiting to every request in the application.
from fastapi import FastAPI
from pyrate_limiter import Duration, Limiter, Rate
from fapi_limiter import (
DynamicBucketFactory,
RateLimiterMiddleware,
setup_inmemory_bucket,
)
app = FastAPI()
limiter = Limiter(
DynamicBucketFactory(setup_inmemory_bucket([Rate(10, Duration.MINUTE)]))
)
app.add_middleware(RateLimiterMiddleware, limiter=limiter)
Dependency (per-route)
Apply rate limiting to specific routes using FastAPI's dependency injection.
from fastapi import Depends, FastAPI
from pyrate_limiter import Duration, Limiter, Rate
from fapi_limiter import DynamicBucketFactory, RateLimiter, setup_inmemory_bucket
app = FastAPI()
limiter = Limiter(
DynamicBucketFactory(setup_inmemory_bucket([Rate(10, Duration.MINUTE)]))
)
@app.get("/limited", dependencies=[Depends(RateLimiter(limiter))])
def limited():
return {"ok": True}
SQLite backend (persistent, multi-process)
use_file_lock=True requires the filelock package.
from fastapi import FastAPI
from pyrate_limiter import Duration, Limiter, Rate
from fapi_limiter import (
DynamicBucketFactory,
RateLimiterMiddleware,
setup_sqlite_bucket,
)
app = FastAPI()
limiter = Limiter(
DynamicBucketFactory(
setup_sqlite_bucket(
[Rate(10, Duration.MINUTE)],
db_path="rate_limiter.db",
use_file_lock=True, # required when sharing across processes
)
)
)
app.add_middleware(RateLimiterMiddleware, limiter=limiter)
Redis backend
Requires the redis package. Both redis.Redis and redis.asyncio.Redis clients work.
from fastapi import FastAPI
from pyrate_limiter import Duration, Limiter, Rate
from redis import Redis
from fapi_limiter import DynamicBucketFactory, RateLimiterMiddleware, setup_redis_bucket
app = FastAPI()
limiter = Limiter(
DynamicBucketFactory(
setup_redis_bucket([Rate(10, Duration.MINUTE)], redis=Redis(host="localhost"))
)
)
app.add_middleware(RateLimiterMiddleware, limiter=limiter)
Response Headers
On every request, the following headers are set:
| Header | Description |
|---|---|
X-RateLimit-Limit |
Maximum requests allowed in the window |
X-RateLimit-Remaining |
Requests remaining in the current window |
X-RateLimit-Reset |
Unix timestamp (ms) when the window resets |
When the limit is exceeded, 429 Too Many Requests is returned and one additional header is set:
| Header | Description |
|---|---|
Retry-After |
Seconds to wait before the client may retry |
Configuration
Both RateLimiterMiddleware and RateLimiter accept the same options:
| Parameter | Type | Default | Description |
|---|---|---|---|
limiter |
Limiter |
required | A pyrate-limiter Limiter instance |
callback |
CallbackFunction |
default_callback |
Called when the limit is exceeded |
identifier |
Callable[[Request], str] |
get_default_identifier |
Extracts a key from the request (e.g. IP + path) |
blocking |
bool |
False |
Whether to block and wait instead of rejecting |
RateLimiterMiddleware also accepts:
| Parameter | Type | Default | Description |
|---|---|---|---|
skip |
SkipFunction | None |
None |
If it returns True, the request bypasses rate limiting |
Custom Callback
The callback is invoked when a request is rate-limited. It receives the Request and a headers dict, and should raise an HTTPException. If it returns without raising, the default 429 is sent:
from fastapi import HTTPException, Request
from fapi_limiter import RateLimiterMiddleware
def my_callback(request: Request, headers=None):
raise HTTPException(status_code=429, detail="Slow down!", headers=headers)
app.add_middleware(RateLimiterMiddleware, limiter=limiter, callback=my_callback)
Custom Identifier
By default the identifier is {request_method}:{client_ip}:{path}. X-Forwarded-For is ignored because clients can forge it. Behind a proxy, have the server resolve the real client address, or every client will share the proxy's limit:
uvicorn main:app --forwarded-allow-ips="<proxy ip>"
You can override the identifier to key by user, API token, etc.:
def by_user(request: Request) -> str:
return request.headers.get("X-User-Id", "anonymous") + ":" + request.url.path
app.add_middleware(RateLimiterMiddleware, limiter=limiter, identifier=by_user)
Skip Function
Use skip on RateLimiterMiddleware to bypass rate limiting for certain requests (e.g. health checks):
def skip_health(request: Request) -> bool:
return request.url.path == "/health"
app.add_middleware(RateLimiterMiddleware, limiter=limiter, skip=skip_health)
Credits
License
Metadata
Release files for fapi-limiter 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| fapi_limiter-0.3.0.tar.gz | 9.2 kB | Without provenance | Details for fapi_limiter-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| fapi_limiter-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for fapi_limiter-0.3.0-py3-none-any.whl |
Total release size: 20.5 kB
Release files / fapi_limiter-0.3.0.tar.gz
| Download URL | fapi_limiter-0.3.0.tar.gz |
|---|---|
| Size | 9.2 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4117f164b3220a128f2172a79d7bf16d7c69ed0580f3660f0f1f3107a0ade4b4
|
|
BLAKE2b-256 checksum How to use checksums |
ab0b5d37bc589b22fe0e25f9d52663f2ee9117776df24e630d74b711ce2491d5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / fapi_limiter-0.3.0-py3-none-any.whl
| Download URL | fapi_limiter-0.3.0-py3-none-any.whl |
|---|---|
| Size | 11.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
b95373312322472859a5dce2c5643ce1ed574c5ed0ec19d430e74791d162417c
|
|
BLAKE2b-256 checksum How to use checksums |
5e4c25fdbe50ff53ec11ca32f977499ac02ef1e29b651585b04697685b94e412
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for fapi-limiter 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.