Skip to content

Rate Limiting Decorators

Rate limiting decorators allow you to apply custom rate limits to specific endpoints, overriding global settings.


Basic Rate Limiting

from djangoapi_guard import SecurityDecorator
from django.http import JsonResponse

guard_deco = SecurityDecorator(config)

@guard_deco.rate_limit(requests=10, window=300)  # 10 requests per 5 minutes
def limited_endpoint(request):
    return JsonResponse({"data": "rate limited"})

Endpoint-Specific Rate Limits

@guard_deco.rate_limit(requests=5, window=300)     # 5 attempts per 5 minutes
def login(request):
    return JsonResponse({"token": "jwt_token"})

@guard_deco.rate_limit(requests=3, window=3600)    # 3 registrations per hour
def register(request):
    return JsonResponse({"status": "user created"})

Geographic Rate Limiting

@guard_deco.geo_rate_limit({
    "US": (100, 3600),    # 100 requests/hour for US
    "CA": (100, 3600),    # 100 requests/hour for Canada
    "CN": (10, 3600),     # 10 requests/hour for China
    "*": (50, 3600)       # 50 requests/hour for others
})
def geo_limited_content(request):
    return JsonResponse({"data": "geographic rate limited"})

Combining with Other Decorators

@guard_deco.require_ip(whitelist=["10.0.0.0/8"])     # Internal network only
@guard_deco.rate_limit(requests=20, window=3600)     # 20 actions per hour
def admin_action(request):
    return JsonResponse({"status": "admin action completed"})

Error Handling

  • 429 Too Many Requests: Rate limit exceeded

Next Steps

For complete API reference, see the Rate Limiting API Documentation.