Python Integration
Below is an example of checking rate limits in a FastAPI application using standard Python requests.
FastAPI Dependency Example
from fastapi import FastAPI, Depends, Request, HTTPException
import httpx
import os
app = FastAPI()
RATESHIELD_KEY = os.getenv("RATESHIELD_API_KEY")
async def rate_limiter(request: Request):
client_ip = request.client.host
async with httpx.AsyncClient() as client:
response = await client.post(
"https://api.rateshield.com/per/endpoint",
headers={"Authorization": f"Bearer {RATESHIELD_KEY}"},
json={
"rate": {"key": client_ip},
"counter_addition": 1
}
)
if response.status_code == 429:
raise HTTPException(status_code=429, detail="Too many requests")
# Optionally handle 401 Unauthorized or API errors
@app.get("/api/data", dependencies=[Depends(rate_limiter)])
async def get_data():
return {"data": "Secure information"}