Without FastAPI¶
Everything so far attached a limit to a FastAPI route. paceapi itself depends
only on Starlette, and has two ways to limit a Starlette app: middleware for
the whole app, and a decorator for one endpoint. Both come from
paceapi.integrations.starlette:
from paceapi import Limiter, authenticated_user, client_ip, first_of
from paceapi.integrations.starlette import PaceMiddleware, limited
The middleware is for FastAPI apps as well. For a FastAPI route, keep using
Limiter.limit().
A limit for the whole app¶
PaceMiddleware counts every
HTTP request before the app chooses a route. Here caller is a key and
TokenAuth is the app's own authentication, both shown further down:
return Starlette(
routes=[Route("/", home), Route("/search", search)],
middleware=[
# Authentication goes first, so that the limit can see who is calling.
Middleware(AuthenticationMiddleware, backend=TokenAuth()),
Middleware(PaceMiddleware, limiter=limiter, limit="100/minute", key=caller),
],
)
Each caller gets one allowance across the whole app. A request over it is
answered by the middleware with a 429, a JSON body, Retry-After and the rate
limit headers, and never reaches your routes.
To enforce several rates, pass a list: limit=["10/second", "1000/day"]. The
scope names the bucket. If you add the middleware twice with the same rate
and key, give each a scope of its own, or every request is counted twice
against one allowance.
Things to know about where the middleware sits:
- It is outside your exception handlers. They never see its 429, nor a
MissingKeyErrorfrom its key. A key used here should returnNonefor a caller it cannot name, not raise an HTTP error. - Order matters. In
middleware=[...]the first one listed runs first. Withapp.add_middleware(...)it is the other way round: the last one added runs first. - CORS. Put
CORSMiddlewareoutsidePaceMiddleware, or a browser cannot read the 429. - Mistakes in its arguments surface late. Starlette builds its middleware
when the server first calls the app, so a rate that cannot be read is raised
then. With
uvicorn --lifespan on, orwith TestClient(app):in a test, that stops the app from starting. With most servers' defaults the app starts and answers every request with a 500.
A limit on one endpoint¶
limited wraps one endpoint:
@limited(limiter, "2/minute", key=caller)
async def search(request: Request) -> JSONResponse:
return JSONResponse({"query": request.query_params.get("q", "")})
It works on a function that takes the request, async or not, and on a method
of an HTTPEndpoint class. Each endpoint keeps a bucket of its own, named
after the function. Give several the same scope to share one bucket. Give
endpoints that one function makes, which all have the same name, a scope
each to keep them apart.
A request over the limit raises
RateLimitExceeded. Starlette
sends it as a 429 with a plain-text body. To answer in your own way, register
an exception handler for the class, as on
Headers and errors.
Keys¶
Outside FastAPI there is nothing to inject, so a key is called with the request and nothing else. The keys that ship with paceapi work as they are, and so does a function of your own that takes the request:
# A signed-in caller is counted as that user, and anyone else by address.
caller = first_of(authenticated_user, client_ip)
authenticated_user names the user that
Starlette's AuthenticationMiddleware found, and returns None when nobody is
signed in. It counts by the user's identity. A user class without one is
counted by display_name, which is only sound if that is unique and the user
cannot change it. The authentication middleware has to run before
PaceMiddleware, or the limit runs before anyone has been identified.
A key written for FastAPI to fill in, such as one that takes
user: User = Depends(current_user), is refused when the middleware or the
decorator is made. Use it with Limiter.limit() on a FastAPI route instead.
In a FastAPI app¶
The middleware gives a FastAPI app one overall limit that runs before routing and before any dependency. And it puts the rate limit headers on every response the app sends, which a limit on a route cannot do by itself. Headers and errors has the details.
The whole Starlette app is in
examples/starlette_app.py.