Skip to main content

# ratelimit-fastapi

Library allows to easily create fastapi endpoints protected by ratelimit

Here is a basic example:

from contextlib import asynccontextmanager
from datetime import timedelta
import random

from ratelimit.ranking.redis import RedisRanking
from fastapi import FastAPI, Depends, Request
from ratelimit.store.redis import RedisStore
from redis.asyncio import Redis

from ratelimit import (
    RateLimitErrorResponse,
    ratelimit,
    LimitRule,
    setup_app,
    BaseUser,
)

# Setup redis connection
redis = Redis.from_url("redis://localhost:6379/1")


# Define user model that will be stored by library. This data is stored for
# determining user's rank
class User(BaseUser):
    address: str

    # Unique id is required to be defined, and it must be unique for each user
    @property
    def unique_id(self):
        return self.address


# Define authentication function, here you need to create instance of a model.
# This function is used as a dependency, so it can use all dependencies, that
# can be used in FastAPI
def auth_func(request: Request):
    return User(address=request.client.host, group="user")


@asynccontextmanager
async def lifespan(fastapi: FastAPI):
    # Setup ratelimit
    setup_app(
        fastapi,
        ranking=RedisRanking(redis, User),  # Ranking stores user's ranks
        store=RedisStore(redis),  # Store stores endpoint related data
        authentication_func=auth_func,  # Register authentication function
    )
    yield

app = FastAPI(lifespan=lifespan)


@app.get(
    "/",
    dependencies=[
        Depends(
            ratelimit(  # Create ratelimiting dependency
                LimitRule(  # Define ratelimiting rule
                    hits=120,  # Max 120 requests
                    batch_time=timedelta(
                        minutes=1
                    ).total_seconds(),  # Per 1 minute
                    block_time=timedelta(minutes=5).total_seconds(), # Time to block user for
                ),
                LimitRule(  # Here can be multiple levels of the limiting rules, named "ranks"
                    hits=120,
                    batch_time=timedelta(minutes=1).total_seconds(),
                    block_time=timedelta(minutes=10).total_seconds(),
                ),
                (  # And rules can be grouped to be in one rank
                    LimitRule(
                        hits=120,
                        batch_time=timedelta(minutes=1).total_seconds(),
                        block_time=timedelta(minutes=5).total_seconds(),
                    ),
                    LimitRule(
                        delay=timedelta(
                            seconds=15
                        ).total_seconds(),  # This rule may allow access only if between requests are delay in 15 seconds or more
                        block_time=timedelta(minutes=1).total_seconds(),
                    ),
                ),
            )
        )
    ],
    responses={
        429: {"model": RateLimitErrorResponse}
    },  # Set response model, to see the correct error schema
)
# Define endpoint as usual
def home(a: int = 10, b: int = 30):
    if a > b:
        a, b = b, a

    if a == b:
        a, b = 10, 30

    return {"random_value": random.randint(a, b)}

More examples at "examples" directory :3

Metadata

Release files for ratelimit-fastapi 1.1.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for ratelimit-fastapi 1.1.3
File Size Uploaded Provenance
ratelimit_fastapi-1.1.3.tar.gz 25.9 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for ratelimit-fastapi 1.1.3
File Interpreter ABI Platform
ratelimit_fastapi-1.1.3-py3-none-any.whl Python 3 none any Details

Total release size: 50.3 kB

Release files / ratelimit_fastapi-1.1.3.tar.gz

Download URL ratelimit_fastapi-1.1.3.tar.gz
Size 25.9 kB
Tags Source
SHA-256 checksum
How to use checksums
68e0785543d956a741df8d3b1f97b90b45cd5a28bc353020fdd982d5aafa47de
BLAKE2b-256 checksum
How to use checksums
0a8c2ab6a827d64cafe123c5b425cc87e360eab4137531dae371814400c42321
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.11.2 Linux/6.1.0-26-amd64

Release files / ratelimit_fastapi-1.1.3-py3-none-any.whl

Download URL ratelimit_fastapi-1.1.3-py3-none-any.whl
Size 24.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
310b84b527aaabc2379eb63c077ece96bb15449daea53a9b3e98ba934c269027
BLAKE2b-256 checksum
How to use checksums
07005c28f024a1a7fd1ce562da6087536dba045c837d8f2b1e7973c110ccd36a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.3 CPython/3.11.2 Linux/6.1.0-26-amd64

Security for ratelimit-fastapi 1.1.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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page