Permissions and throttling in Django REST Framework (DRF) help secure APIs by controlling who can access endpoints and how frequently clients can send requests.
Permissions determine whether a request should be allowed or denied.
IsAuthenticatedIsAdminUserAllowAnyIsAuthenticatedOrReadOnlyDjangoModelPermissions
# 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 protects APIs from excessive usage.
AnonRateThrottleUserRateThrottleScopedRateThrottle
# 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]
# Enforce authentication globally
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
# 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',
}
}
Simulate how permissions (Roles) and throttling (Rate Limits) interact.
Rule: Rate limit is 5 requests per 10 seconds.