slowapi

noun

say it: “SLOH-ay-pee-EYE” /sloʊ ˌeɪ pi ˈaɪ/

A Python package that adds rate limits to FastAPI routes, such as 5 tries a minute from one address, and refuses the rest with 429 Too Many Requests.

What is slowapi?

slowapi is a package that adds rate limits to FastAPI routes, such as 5 sign-in tries a minute from one address. @limiter.limit("5/minute") goes under the route's decorator, the route takes request: Request, and a try over the limit raises RateLimitExceeded, which a handler answers with 429 Too Many Requests.

from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address

limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.post("/sign-in")
@limiter.limit("5/minute")
def sign_in(request: Request):
    return {"detail": "Wrong email or password"}

client = TestClient(app)
print([client.post("/sign-in").status_code for _ in range(6)])   # [200, 200, 200, 200, 200, 429]

In a sentence

  • “The sixth try in a minute got a 429 from slowapi.”
  • “slowapi limits the sign-in route to 5 tries a minute, so a list of 1,000 guesses takes hours.”

Level: Freelancer · More FastAPI terms at this level

Updated