The Django Rest Framework includes the AnonRateThrottle, a throttling class that limits the number of requests that anonymous users can make within a specific time frame. Limiting the number of requests made to an API within a certain period is a common method of preventing abuse.

The API can handle requests in a fair and sustainable manner by restricting the number of requests through throttling.

The AnonRateThrottle class specifically limits the rate of requests made by anonymous users, based on their IP address. This means that the rate of requests made by authenticated users, who have logged in to the API, is not limited.

To use the AnonRateThrottle class, you first need to include it in the list of throttle classes in your Django Rest Framework settings. Here’s an example:

        'anon': '100/day',

This example sets the rate limit for anonymous users to 100 requests per day. You can adjust the rate limit to suit your needs.

Note that if you have multiple throttle classes in the list, they will be applied in the order they are listed. In this example, the AnonRateThrottle class is the only throttle class, so it will be applied to all requests. If you have additional throttle classes, they will be applied in addition to the AnonRateThrottle.

A Simple project on AnonRateThrottle in Django

  1. Start by creating a new Django project and app:
django-admin startproject myproject
cd myproject
python startapp myapp
  1. Install Django Rest Framework:
pip install djangorestframework
  1. Add ‘rest_framework’ to the list of installed apps in myproject/
    # other apps here
  1. Create a simple API view that returns a “Hello, world!” message:
# myapp/
from rest_framework.views import APIView
from rest_framework.response import Response

class HelloWorldView(APIView):
    def get(self, request):
        return Response("Hello, world!")
  1. In myapp/, add a URL pattern for the view:
from django.urls import path
from .views import HelloWorldView

urlpatterns = [
    path('hello/', HelloWorldView.as_view()),
  1. Finally, in myproject/, add the AnonRateThrottle to the list of throttle classes:
        'anon': '10/minute',

This sets the rate limit for anonymous users to 10 requests per minute. You can adjust the rate limit to suit your needs.

  1. Run the server:
python runserver
  1. Open your web browser and go to http://localhost:8000/hello/. You should see the “Hello, world!” message.
  2. Try making more than 10 requests to the API within a minute using a tool like curl or Postman. After the 10th request, you should start seeing a “Throttled” response.

That’s it! You’ve successfully used the AnonRateThrottle in Django Rest Framework to limit the rate of requests made by anonymous users to your API.