Skip to main content

A FastAPI rate limiting library.

Project description

Farl

Python 3.11+ PyPI version Coverage Status Code Coverage License

A powerful and flexible FastAPI rate limiting library that provides comprehensive rate limiting capabilities for your FastAPI applications.

Features

  • Easy Integration: Simple setup with FastAPI applications
  • Flexible Configuration: Support for various rate limiting strategies
  • Multiple Backends: In-memory and Redis backend support
  • Comprehensive Protection: Request rate limiting with customizable rules
  • Monitoring: Built-in metrics and logging capabilities
  • Dependency Injection: FastAPI-style dependency injection support

Installation

pip install farl

Optional Dependencies

For Redis backend support:

pip install farl[redis]

For development:

pip install farl[dev,tests]

Quick Start

from fastapi import Depends, FastAPI

from farl import Farl
from farl import rate_limit as rate_limit_dep
from farl.decorators import rate_limit


app = FastAPI()

farl = Farl()


@app.get("/api/data")
@rate_limit("10/minute", farl=farl)  # Allow 10 requests per minute
@rate_limit("100/day", farl=farl)  # Allow 100 requests per day
async def get_data():
    return {"message": "Hello, World!"}


@app.get(
    "/api/limited",
    dependencies=[
        # Allow 1 requests per minute
        Depends(rate_limit_dep({"amount": 1}, farl=farl)),
    ],
)
async def limited_endpoint():
    return {"message": "This endpoint is rate limited"}

Configuration

Basic Rate Limiting

from fastapi import Depends, FastAPI

from farl import Farl
from farl import rate_limit as rate_limit_dep
from farl.decorators import rate_limit


# Create a rate limiter instance
farl = Farl()

app = FastAPI()


@app.get("/my_function")
@rate_limit(
    "100/hour",
    farl=farl,
)
async def my_function():
    pass


# Use as dependency
@app.get(
    "/endpoint",
    dependencies=[
        Depends(
            rate_limit_dep(
                {"amount": 50, "time": "minute"},
                farl=farl,
            )
        ),
    ],
)
async def endpoint():
    return {"status": "ok"}

Advanced Configuration

from fastapi import Depends, FastAPI
from pydantic import RedisDsn

from farl import AsyncFarl, rate_limit


# Using Redis backend
redis_uri = RedisDsn("redis://")  # or "redis://"
farl = AsyncFarl(redis_uri=redis_uri)

app = FastAPI()


@app.get(
    "/",
    dependencies=[
        Depends(
            rate_limit(
                {"amount": 1},
                farl=farl,
            ),
        )
    ],
)
async def complex_endpoint():
    return {"message": "Multiple rate limits applied"}

Middleware Usage

from fastapi import Depends, FastAPI
from pydantic import RedisDsn

from farl import AsyncFarl, FarlMiddleware, rate_limit


# Using Redis backend
redis_uri = RedisDsn("redis://")  # or "redis://"
farl = AsyncFarl(redis_uri=redis_uri)

app = FastAPI()
app.add_middleware(
    FarlMiddleware,
    farl=farl,
)


@app.get(
    "/",
    dependencies=[
        Depends(
            rate_limit({"amount": 1}),
        )
    ],
)
async def pre_minute_1_request():
    return {"message": "ok"}

Rate Limit Formats

Farl supports various rate limit formats:

  • "100/minute" - 100 requests per minute
  • "1000/hour" - 1000 requests per hour
  • "10000/day" - 10000 requests per day
  • "50/second" - 50 requests per second

Error Handling

from farl.exceptions import RateLimitExceeded
from fastapi import Request, HTTPException

@app.exception_handler(RateLimitExceeded)
async def rate_limit_handler(request: Request, exc: RateLimitExceeded):
    return HTTPException(
        status_code=429,
        detail=f"Rate limit exceeded: {exc.detail}",
        headers={"Retry-After": str(exc.retry_after)}
    )

Development

Running Tests

# Install development dependencies
pip install -e .[dev,tests]

# Run tests
pytest

# Run tests with coverage
pytest --cov=farl --cov-report=html

Code Quality

# Format code
ruff format

# Lint code
ruff check

Requirements

  • Python 3.11+
  • FastAPI 0.116.1+
  • limits 5.4.0+

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Changelog

v0.0.2

  • Initial release with core rate limiting functionality
  • FastAPI integration
  • Multiple backend support
  • Comprehensive testing suite

Support

If you encounter any issues or have questions, please file an issue on the GitHub issue tracker.

Author

nafnix - uwu@nafnix.com

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

farl-0.0.3.tar.gz (41.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

farl-0.0.3-py3-none-any.whl (12.8 kB view details)

Uploaded Python 3

File details

Details for the file farl-0.0.3.tar.gz.

File metadata

  • Download URL: farl-0.0.3.tar.gz
  • Upload date:
  • Size: 41.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.15

File hashes

Hashes for farl-0.0.3.tar.gz
Algorithm Hash digest
SHA256 f85597872940cc31f69fb438116be93798c462557ee20df59ed770f907b9617f
MD5 319ee3835c12c5688b97280eade9631c
BLAKE2b-256 291ad7fe3088b3036477a8b325d2fee60cd3deecd471a944776260e23047a874

See more details on using hashes here.

File details

Details for the file farl-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: farl-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 12.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.7.15

File hashes

Hashes for farl-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 e0e3c0fa2f3bd2ede8d26fd4256b0e2b88365bd53f8800cdc8a88d2e074fbc89
MD5 99fab078a605570de3096d449a73735a
BLAKE2b-256 c1abd79557e54eaa226edc2a3c65703eee3b59bc726b72eb95dd6a92e1b09f76

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page