Custom header styles¶
A header style controls which rate limit headers a response carries. paceapi ships X-RateLimit-* headers (the default) and the IETF draft RateLimit headers. A custom one is a class with a single method.
Example: reset as a Unix timestamp¶
The built-in style reports the reset as seconds remaining. Some APIs report an absolute Unix timestamp instead, and clients written for them expect it:
@dataclass(frozen=True)
class ResetAtAClockTime:
"""`X-RateLimit-*` headers with the reset as an absolute Unix timestamp.
Some APIs and their clients expect this form. The built-in style sends
seconds remaining, which does not depend on client and server clocks agreeing.
"""
clock: Callable[[], float] = time.time
def headers(self, decision: Decision) -> Mapping[str, str]:
return {
"X-RateLimit-Limit": str(decision.limit),
"X-RateLimit-Remaining": str(decision.remaining),
"X-RateLimit-Reset": str(math.ceil(self.clock() + decision.reset_after)),
}
Full example: examples/header_style.py.
Contract¶
HeaderStyle has one method, headers(), which receives a Decision and returns the headers describing it.
- Handles any decision: Allowed or denied, including one for a rate your app never uses.
too_many_requests()passes a synthetic decision to discover which headers a style emits for the OpenAPI schema. - Called once per limit: A request that passes several limits calls
headers()for each, and the response carries the headers of the limit closest to exhaustion. Keep it to formatting a few numbers. Retry-Afteris not part of the style: The limiter adds it to every 429, even withheader_style=None.