Instagram
youtube
Facebook
Twitter

Throttling in Django Rest Framework

In this tutorial, we will explore the concept of throttling in Django Rest Framework (DRF).

Throttling is a crucial feature for controlling the rate of incoming requests to our APIs. It helps prevent abuse and ensures fair usage, especially when dealing with public APIs.

What is API Throttling?

  • API throttling is the practice of limiting the number of requests a client can make to our API within a specific time period.

  • This prevents a single client from overloading the server with too many requests, ensuring fair usage and system stability.

Throttling Types in DRF

DRF provides several built-in throttling strategies to control request rates. Some of them are:

  • AnonRateThrottle: Limits requests from anonymous users.

  • UserRateThrottle: Limits requests based on user.

  • ScopedRateThrottle: Allows setting custom throttling rates based on view scope.

Enabling and Configuring Throttling

First, we have to configure throttling in our settings.py file before using it. To configure it, please add the code given below to your project's settings.py file.

 

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': [
        'rest_framework.throttling.AnonRateThrottle',
        'rest_framework.throttling.UserRateThrottle',
        'rest_framework.throttling.ScopedRateThrottle',
    ],
    'DEFAULT_THROTTLE_RATES': {
        'anon': '5/minute',
        'user': '2/minute',
        'custom': '10/hour',
    },
}

In above code, associated rate limits define how many requests each class or scope is allowed within a given time period. These settings ensure controlled and fair usage of the API and prevent abuse.

Views.py

from rest_framework.generics import ListAPIView, CreateAPIView
from .models import Students
from .serializers import StudentsSerializer
from rest_framework.throttling import AnonRateThrottle

class StudentsListCreateView(ListAPIView, CreateAPIView):
    queryset = Students.objects.all()
    serializer_class = StudentsSerializer
    throttle_classes = [AnonRateThrottle]

In this tutorial, we are using AnonRateThrottle to limit anonymous users requests. You can also use any other strategy. The throttle_classes attribute is set to [AnonRateThrottle], which means that anonymous users (unauthenticated users) will be subject to rate limiting as defined by the AnonRateThrottle class.

In simple words, if an anonymous user attempts to send more requests than the set limit defined in the settings.py file, their requests will be temporarily restricted or 'throttled' for a certain period.

Now, let's check it is working or not.

Properly working!