← Back to Chapters

Permissions & Throttling in Django REST Framework

? Permissions & Throttling in Django REST Framework

? Quick Overview

Permissions and throttling in Django REST Framework (DRF) help secure APIs by controlling who can access endpoints and how frequently clients can send requests.

? Key Concepts

  • Permissions restrict access based on user roles or authentication
  • Throttling limits request rates to prevent abuse

? Permissions in DRF

Permissions determine whether a request should be allowed or denied.

  • IsAuthenticated
  • IsAdminUser
  • AllowAny
  • IsAuthenticatedOrReadOnly
  • DjangoModelPermissions

? Setting Permissions on Views

? View Code Example
# Restrict access to authenticated users only
from rest_framework.permissions import IsAuthenticated
from rest_framework import viewsets

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = [IsAuthenticated]

⏱️ Throttling in DRF

Throttling protects APIs from excessive usage.

  • AnonRateThrottle
  • UserRateThrottle
  • ScopedRateThrottle

? Setting Throttling on Views

? View Code Example
# Apply throttling for both authenticated and anonymous users
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle
from rest_framework import viewsets

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    throttle_classes = [UserRateThrottle, AnonRateThrottle]

⚙️ Global Configuration

Default Permissions

? View Code Example
# Enforce authentication globally
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ],
}

Default Throttling

? View Code Example
# Configure request limits
REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.UserRateThrottle',
        'rest_framework.throttling.AnonRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'user': '1000/day',
        'anon': '100/day',
    }
}

? Explanation

  • Permissions ensure only authorized access
  • Throttling prevents API overuse
  • Global settings simplify enforcement

? Interactive Simulator

Simulate how permissions (Roles) and throttling (Rate Limits) interact.
Rule: Rate limit is 5 requests per 10 seconds.

Requests: 0 / 5
> Ready to simulate requests...

✅ Tips & Best Practices

  • Use least-privilege permissions
  • Throttle public endpoints
  • Use scoped throttling for fine control

? Try It Yourself

  • Create a custom permission class
  • Change throttle limits and test with API calls
  • Trigger a 429 error intentionally