Skip to content

FastAPI

Setup

pip install drogue[fastapi]
from fastapi import FastAPI
from drogue.adapters.fastapi import DrogueLimiter

app = FastAPI()
limiter = DrogueLimiter(app, default_limits=["100/minute"])

Decorator

@app.get("/api/data")
@limiter.limit("10/minute")
async def get_data():
    return {"data": "value"}

No request: Request parameter needed.

Dependency injection

from fastapi import Depends

@app.get("/api/data")
async def get_data(rate_limit=Depends(limiter.dependency("10/minute"))):
    return {"data": "value"}

WebSocket rate limiting

@app.websocket("/ws")
@limiter.limit_ws("100/minute")
async def websocket_endpoint(websocket):
    await websocket.accept()

Custom key function

from drogue.core.identity import UserExtractor

@app.get("/api/data")
@limiter.limit("10/minute", key_func=UserExtractor())
async def get_data(): ...

Algorithm selection

from drogue.core.rules.rule import AlgorithmType

@app.get("/api/data")
@limiter.limit("10/minute", algorithm=AlgorithmType.SLIDING_WINDOW)
async def get_data(): ...

Blocking mode

@app.get("/api/data")
@limiter.limit("10/minute", block=True, timeout=5.0)
async def get_data(): ...

Shadow mode

Test rules without enforcing:

@app.get("/api/data")
@limiter.limit("10/minute", shadow=True)
async def get_data(): ...

stats = limiter.get_shadow_stats()

Challenges (CAPTCHA escalation)

Serve a challenge widget on page denials instead of a bare 429. Requires challenge_enabled in the config plus a signing key and Turnstile keys (either in the config or via challenge_provider=):

import os
from drogue.core.config import DrogueConfig

config = DrogueConfig(
    challenge_enabled=True,
    challenge_signing_key=os.environ["DROGUE_CHALLENGE_SIGNING_KEY"],
    challenge_site_key=os.environ["TURNSTILE_SITE_KEY"],
    challenge_secret=os.environ["TURNSTILE_SECRET"],
)

limiter = DrogueLimiter(app, storage=storage, config=config)

GET /drogue/challenge renders the interstitial, POST /drogue/verify checks the answer and sets the signed drogue_pass cookie on success. Only GET requests accepting text/html see the interstitial; API clients keep the normal JSON denial. Full details in Challenges (CAPTCHA).

Rate limit headers

Header Description
X-RateLimit-Limit Maximum requests allowed
X-RateLimit-Remaining Requests remaining
X-RateLimit-Reset Unix timestamp when window resets
Retry-After Seconds until next request (only on 429)