Rate-limiter for FastAPI with the possibility of user-based rate limits
Project description
FastAPI rate limiter
This package adds a rate limiter to FastAPI using Redis.
Installation
First install Redis, then install the package using:
pip install fastapi-user-limiter
Usage
You can use the rate_limit
decorator to put a single rate limit on an endpoint:
from fastapi_user_limiter.limiter import RateLimiter, rate_limit
from fastapi import FastAPI, Request
app = FastAPI()
rate_limiter = RateLimiter()
# 2 requests max per 5 seconds
@app.get("/single")
@rate_limit(rate_limiter, 2, 5)
async def read_single(request: Request):
return {"Hello": "World"}
To put multiple rate limits on the same endpoint (with different window size and maximum request counts), use the
multi_rate_limit
decorator. Each multi_rate_limit
decorator on a particular endpoint requires an ID as its first arg.
This ID must be unique among the multi_rate_limit
decorators on that endpoint:
from fastapi_user_limiter.limiter import RateLimiter, multi_rate_limit
from fastapi import FastAPI, Request
app = FastAPI()
rate_limiter = RateLimiter()
# 1 request max per second, 3 requests max per 10 seconds
@app.get("/multi")
@multi_rate_limit(1, rate_limiter, 1, 1)
@multi_rate_limit(2, rate_limiter, 3, 10)
async def read_multi(request: Request):
return {"Hello": "There"}
The aforementioned examples can be found in example.py
(use uvicorn example:app --reload
to run).
NOTE: Every endpoint handler with the rate limiter decorator needs to have request
(of type fastapi.Request
)
as its first argument.
Future features
The package will soon have the additional feature of allowing each user account to have a different rate limit for each endpoint.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for fastapi_user_limiter-0.2.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | a96307573c76e6e77daf12b4cd19d95a27365a5a7e2f72dd3d7adb48fa539b2a |
|
MD5 | aac5cccbff2fb403b0b4427bb0162fdc |
|
BLAKE2b-256 | 132c33417ab372780c19582b5cb3d5f51f78995b2891ef4449474732051f61e9 |
Hashes for fastapi_user_limiter-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3fe7f4728717930834bd2666ac399b8d540039928f82a33c9e1728df415349f2 |
|
MD5 | 57ef9b695afe1104006c8b761add535c |
|
BLAKE2b-256 | 817a48b30a546143d24c2d1f2a8c3faf1e4c723f1f03b4df6381fd6bf59d33f3 |