Headers and errors¶
The headers on a response¶
| Header | What it says |
|---|---|
X-RateLimit-Limit |
How many requests the rate allows in one period |
X-RateLimit-Remaining |
How many are left right now |
X-RateLimit-Reset |
Whole seconds from now until the full allowance is back |
Retry-After |
Only on a 429: whole seconds to wait before trying again |
X-RateLimit-Reset is a number of seconds, not a time of day, so it means the
same thing whether or not the caller's clock agrees with the server's.
When several limits apply to one request, the headers describe the one the caller is closest to using up.
Responses the endpoint builds itself¶
A limit on a route adds the headers to the response FastAPI builds from what
your endpoint returns. When an endpoint returns a Response object of its
own, FastAPI sends it exactly as it is, and the headers are not on it. The
same is true of an error response. The limit still applies in both cases.
PaceMiddleware puts the
headers on every response the app sends, whatever made it. The one exception
is the 500 for an error nothing handled, which Starlette makes outside every
middleware:
# FastAPI sends a response that an endpoint returns exactly as it is, and
# builds an error response somewhere else again. The middleware sees them
# all, and puts the headers on.
app.add_middleware(PaceMiddleware, limiter=limiter)
reports = [Depends(limiter.limit("2/minute", scope="reports"))]
@app.get("/report.csv", dependencies=reports)
async def report() -> Response:
return Response("day,total\n", media_type="text/csv")
@app.get("/reports/{year}", dependencies=reports)
async def old_report(year: int) -> Response:
raise HTTPException(status_code=404, detail=f"There is no report for {year}.")
With no limit of its own, adding headers is all the middleware does. It can
also carry a limit for the whole app, which
Without FastAPI describes. The
headers then describe whichever limit the caller is closest to using up.
Turning the headers off, or changing them¶
Limiter(headers=None) sends none of the X-RateLimit-* headers. A 429 still
carries Retry-After.
To send other names or formats, write a class with a headers(decision) method
and pass an instance of it as headers. See
HeaderStyle.
The 429 response¶
A request over the limit raises
RateLimitExceeded. It is one
of Starlette's HTTPExceptions, so FastAPI already knows how to send it.
A handler registered for starlette.exceptions.HTTPException receives it too.
One registered for fastapi.HTTPException does not, because that class is a
narrower one that paceapi, which does not depend on FastAPI, cannot raise.
To give it a response of its own, register a handler for the class. A 429
that PaceMiddleware sends for its own limit is made outside your handlers and
does not pass through them.
@app.exception_handler(RateLimitExceeded)
async def slow_down(_: Request, error: RateLimitExceeded) -> JSONResponse:
headers = dict(error.headers or {})
body = {"error": "slow_down", "retry_after_seconds": int(headers["Retry-After"])}
return JSONResponse(body, status_code=error.status_code, headers=headers)
error.decision holds the details of the decision, and error.headers holds
the headers the default response would have carried. Pass them on:
well-behaved clients wait for as long as Retry-After says.