This project has been archived by its maintainers, and is no longer receiving any updates.
FastAPI Limiter
FastAPI-Limiter is a rate limiting tool for fastapi routes, powered by pyrate-limiter.
🦜🕸️
NOTE: This is a fork of (https://github.com/long2ice/fastapi-limiter), currently because the original maintainer @long2ice has not published the latest version which supports FastAPI middleware.
Table of Contents
Introduction
FastAPI-Limiter is a rate limiting tool for fastapi routes, powered by pyrate-limiter.
Quick Start
Since this is just a package, and not a service, there is no real "run" action. But you can run the tests immediately.
Here are a list of available commands via make.
Bare Metal (i.e. your machine)
make install- install the required dependencies.make test- runs the tests.
Docker
make build-docker- build the docker image.make run-docker- run the docker compose services.make test-docker- run the tests in docker.make clean-docker- remove all docker containers etc.
Installation
For Dev work on the repo
Install uv, (if you haven't already)
https://docs.astral.sh/uv/getting-started/installation/#installation-methods
brew install uv
Initialise pre-commit (validates ruff on commit.)
uv run pre-commit install
Install dependencies (including dev dependencies)
uv sync
If you are adding a new dev dependency, please run:
uv add --dev {your-new-package}
Namespaces
Packages all share the same namespace ab_core. To import this package into
your project:
from ab_core.template import placeholder_func
We encourage you to make your package available to all of ab via this
ab_core namespace. The goal is to streamline development, POCs and overall
collaboration.
Usage
Adding the dependency to your project
The library is available on PyPI. You can install it using the following command:
Using pip:
pip install ab-fastapi-limiter
Using UV
Note: there is currently no nice way like poetry, hence we still needd to provide the full url. https://github.com/astral-sh/uv/issues/10140
Add the dependency
uv add ab-fastapi-limiter
Using poetry:
Then run the following command to install the package:
poetry add ab-fastapi-limiter
How tos
Quick Start
FastAPI-Limiter is simple to use, which just provides a dependency RateLimiter. The following example allows 2 requests per 5 seconds on route /.
import uvicorn
from fastapi import Depends, FastAPI
from pyrate_limiter import Duration, Limiter, Rate
from ab_core.fastapi_limiter.depends import RateLimiter
app = FastAPI()
@app.get(
"/",
dependencies=[Depends(RateLimiter(limiter=Limiter(Rate(2, Duration.SECOND * 5))))],
)
async def index():
return {"msg": "Hello World"}
if __name__ == "__main__":
uvicorn.run("main:app", reload=True)
Usage
RateLimiter
RateLimiter accepts the following parameters:
limiter: Apyrate_limiter.Limiterinstance that defines the rate limiting rules.identifier: A callable to identify the request source, default is by IP + path.callback: A callable invoked when the rate limit is exceeded, default raisesHTTPExceptionwith429status code.blocking: Whether to block the request when the rate limit is exceeded, default isFalse.skip: An async callable that takes a request and returnsTrueto skip rate limiting, default isNone.
Identifier
Identifier of route limit, default is ip + path, you can override it such as userid and so on.
async def default_identifier(request: Union[Request, WebSocket]):
forwarded = request.headers.get("X-Forwarded-For")
if forwarded:
ip = forwarded.split(",")[0]
elif request.client:
ip = request.client.host
else:
ip = "127.0.0.1"
return ip + ":" + request.scope["path"]
Callback
Callback when rate limit is exceeded, default raises HTTPException with 429 status code.
def default_callback(*args, **kwargs):
raise HTTPException(
HTTP_429_TOO_MANY_REQUESTS,
"Too Many Requests",
)
Multiple limiters
You can use multiple limiters in one route.
@app.get(
"/multiple",
dependencies=[
Depends(RateLimiter(limiter=Limiter(Rate(1, Duration.SECOND * 5)))),
Depends(RateLimiter(limiter=Limiter(Rate(2, Duration.SECOND * 15)))),
],
)
async def multiple():
return {"msg": "Hello World"}
Note that you should keep the stricter limiter (lower seconds/times ratio) first.
Skip rate limiting
You can pass a skip callable to RateLimiter to conditionally skip rate limiting for a specific route. The callable receives the request and should return True to skip.
from fastapi.requests import Request
async def skip(request: Request):
return request.scope["path"] == "/skip"
@app.get(
"/skip",
dependencies=[
Depends(RateLimiter(limiter=Limiter(Rate(1, Duration.SECOND * 5)), skip=skip))
],
)
async def skip_route():
return {"msg": "This route skips rate limiting"}
Middleware
You can also use RateLimiterMiddleware to apply rate limiting globally to all routes without adding dependencies to each route individually.
from fastapi import FastAPI
from pyrate_limiter import Duration, Limiter, Rate
from ab_core.fastapi_limiter.middleware import RateLimiterMiddleware
app = FastAPI()
app.add_middleware(
RateLimiterMiddleware,
limiter=Limiter(Rate(2, Duration.SECOND * 5)),
)
@app.get("/")
async def index():
return {"msg": "Hello World"}
RateLimiterMiddleware accepts the same identifier, callback, blocking, and skip parameters as RateLimiter.
Path-based middleware
Use PathBasedRateLimiterMiddleware when you only want middleware rate limiting to apply to routes under a specific prefix.
from fastapi import FastAPI
from pyrate_limiter import Duration, Limiter, Rate
from ab_core.fastapi_limiter.middleware import PathBasedRateLimiterMiddleware
app = FastAPI()
app.add_middleware(
PathBasedRateLimiterMiddleware,
limiter=Limiter(Rate(2, Duration.SECOND * 5)),
path_prefix="/path/based",
)
@app.get("/")
async def index():
return {"msg": "Not rate limited by this middleware"}
@app.get("/path/based/1")
async def path_based_route_1():
return {"msg": "Rate limited"}
@app.get("/path/based/2")
async def path_based_route_2():
return {"msg": "Rate limited"}
PathBasedRateLimiterMiddleware accepts:
limiter: Requiredpyrate_limiter.Limiterinstance.path_prefix: Required string prefix used to decide which request paths are rate limited.identifier: Optional identifier callable (defaults todefault_identifier).callback: Optional callback callable when the limit is exceeded (defaults todefault_middleware_callback).blocking: Optional bool passed totry_acquire_async(defaults toFalse).
Routes not starting with path_prefix are skipped by this middleware.
Rate limiting within a websocket
While the above examples work with REST requests, FastAPI also allows easy usage of websockets, which require a slightly different approach.
Because websockets are likely to be long lived, you may want to rate limit in response to data sent over the socket.
You can do this by rate limiting within the body of the websocket handler:
from ab_core.fastapi_limiter.depends import WebSocketRateLimiter
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
ratelimit = WebSocketRateLimiter(limiter=Limiter(Rate(1, Duration.SECOND * 5)))
while True:
try:
data = await websocket.receive_text()
await ratelimit(websocket, context_key=data) # NB: context_key is optional
await websocket.send_text("Hello, world")
except HTTPException:
await websocket.send_text("Hello again")
Formatting and linting
We use Ruff as the formatter and linter. The pre-commit has hooks which runs checking and applies linting automatically. The CI validates the linting, ensuring main is always looking clean.
You can manually use these commands too:
make lint- check for linting issues.make format- fix linting issues.
CICD
Publishing to PyPI
We publish to PyPI using Github releases. Steps are as follows:
- Manually update the version in
pyproject.tomlfile using a PR and merge to main. Useuv version --bump {patch/minor/major}to update the version. - Create a new release in Github with the tag name as the version number. This
will trigger the
publishworkflow. In the Release window, type in the version number and it will prompt to create a new tag. - Verify the release in PyPI
Metadata
Release files for ab-fastapi-limiter 0.2.3
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 |
|---|---|---|---|---|
| ab_fastapi_limiter-0.2.3.tar.gz | 9.4 kB | Without provenance | Details for ab_fastapi_limiter-0.2.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ab_fastapi_limiter-0.2.3-py3-none-any.whl | Python 3 | none | any | Details for ab_fastapi_limiter-0.2.3-py3-none-any.whl |
Total release size: 18.9 kB
Release files / ab_fastapi_limiter-0.2.3.tar.gz
| Download URL | ab_fastapi_limiter-0.2.3.tar.gz |
|---|---|
| Size | 9.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b8bbb52515a35b5a7ffcb5cc858a210e8ce940af7fc2773306790155a484141a
|
|
BLAKE2b-256 checksum How to use checksums |
81169d267575ebbc5b72687735513b9af6e7f3d0eef5a66043e4b1b73d649dc5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","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 / ab_fastapi_limiter-0.2.3-py3-none-any.whl
| Download URL | ab_fastapi_limiter-0.2.3-py3-none-any.whl |
|---|---|
| Size | 9.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
890dc24e8285a58e71a69cae3d863285a7e4be04f20839028aeace7fdc07c853
|
|
BLAKE2b-256 checksum How to use checksums |
64e2822de82ef6651d951d8be43e026e34c91ab624757dd6328668cf7a8eb932
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","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 ab-fastapi-limiter 0.2.3
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.