Django REST framework authentication and pagination
last modified November 22, 2026 Python 3.15
The article Django REST framework built a book API with serializers, viewsets, routers, and permissions. It used the default authentication, which relies on Django's session and on HTTP Basic authentication, and it returned every book in one response. Clients other than a browser usually log in with a token instead, and a list must be split into pages and narrowed by filters as it grows. In this article we add token and JWT authentication, pagination, filtering, search, ordering, and throttling to a book API, and test them. The examples use Django 6.1, Django REST framework 3.18, Simple JWT 5.5, django-filter 26.2, and Python 3.15.
The example project
The project is created with uv; the steps are explained in Django introduction.
The commands below create a project directory, install Django together with djangorestframework, generate the
project with the configuration package config, start the app books, and create the
folder demos for demo scripts. The other packages are added in the sections that use them.
$ mkdir bookapi $ cd bookapi $ uv init --bare $ uv add django djangorestframework $ uv run django-admin startproject config . $ uv run python manage.py startapp books $ mkdir demos
The trailing dot in startproject config . creates manage.py and the
config package in the current directory. Both rest_framework and the new app are
added to INSTALLED_APPS in config/settings.py; the other entries are generated by
startproject.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'books',
]
The listings in this article are of two kinds. A listing with a solid blue border and the label Project
file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed
amber border and the label Demo script is a small helper in the demos folder; it sets up
Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are
not part of the application; we run one from the project directory with uv run python -m
demos.name.
Books with owners
Every book has an owner, a foreign key to the user model, so that the API can tell whose book it is. The model orders the books by title; pagination needs a stable order.
from django.conf import settings
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=60)
published = models.PositiveSmallIntegerField()
price = models.DecimalField(max_digits=6, decimal_places=2)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,
related_name='books')
class Meta:
ordering = ['title']
def __str__(self):
return self.title
We create the tables.
$ uv run python manage.py makemigrations books
Migrations for 'books':
books/migrations/0001_initial.py
+ Create model Book
$ uv run python manage.py migrate | tail -n 2
Applying books.0001_initial... OK
Applying sessions.0001_initial... OK
Sample data
The script seed.py creates the users alice and bob and 24 books. Books published before 2010
belong to alice, the newer ones to bob. The script deletes both users first, which deletes their books too, so
it can be run again.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.contrib.auth.models import User
from books.models import Book
BOOKS = [
('Clean Code', 'Robert C. Martin', 2008, '37.50'),
('Clean Architecture', 'Robert C. Martin', 2017, '36.99'),
('The Clean Coder', 'Robert C. Martin', 2011, '32.99'),
('Fluent Python', 'Luciano Ramalho', 2022, '59.99'),
('Refactoring', 'Martin Fowler', 2018, '47.99'),
('Patterns of Enterprise Application Architecture', 'Martin Fowler', 2002, '59.00'),
('The Pragmatic Programmer', 'Andrew Hunt', 1999, '41.99'),
('Two Scoops of Django', 'Daniel Feldroy', 2020, '49.95'),
('Design Patterns', 'Erich Gamma', 1994, '54.99'),
('Code Complete', 'Steve McConnell', 2004, '44.99'),
('The Mythical Man-Month', 'Frederick Brooks', 1975, '29.99'),
('Working Effectively with Legacy Code', 'Michael Feathers', 2004, '52.99'),
('Domain-Driven Design', 'Eric Evans', 2003, '64.99'),
('Effective Python', 'Brett Slatkin', 2019, '39.99'),
('Python Crash Course', 'Eric Matthes', 2023, '34.99'),
('Test-Driven Development', 'Kent Beck', 2002, '41.50'),
('Designing Data-Intensive Applications', 'Martin Kleppmann', 2017, '49.99'),
('Introduction to Algorithms', 'Thomas H. Cormen', 2009, '89.99'),
('Programming Pearls', 'Jon Bentley', 1999, '31.99'),
('Architecture Patterns with Python', 'Harry Percival', 2020, '45.99'),
('Serious Python', 'Julien Danjou', 2018, '29.95'),
('Python Testing with pytest', 'Brian Okken', 2022, '39.95'),
('Release It!', 'Michael T. Nygard', 2018, '42.95'),
('Python Cookbook', 'David Beazley', 2013, '49.99'),
]
User.objects.filter(username__in=['alice', 'bob']).delete()
alice = User.objects.create_user('alice', password='s3cret-alice')
bob = User.objects.create_user('bob', password='s3cret-bob')
Book.objects.bulk_create(
Book(title=title, author=author, published=year, price=price,
owner=alice if year < 2010 else bob)
for title, author, year, price in BOOKS
)
for user in (alice, bob):
print(user.username, user.books.count())
The output shows how many books each user owns.
$ uv run python -m demos.seed alice 11 bob 13
The API and the current user
The serializer shows the owner's user name as a read-only field, so a client cannot choose the owner.
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
owner = serializers.ReadOnlyField(source='owner.username')
class Meta:
model = Book
fields = ['id', 'title', 'author', 'published', 'price', 'owner']
The viewset provides the list, detail, create, update, and delete actions, and perform_create()
makes the user of the request the owner of a new book. The function view whoami reports who the
request belongs to. The attribute successful_authenticator holds the authentication class that
recognized the user, or None for an anonymous request. An anonymous user has an empty user name,
which we turn into None.
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
@api_view(['GET'])
def whoami(request):
authenticator = request.successful_authenticator
return Response({
'user': request.user.username or None,
'authenticator': type(authenticator).__name__ if authenticator else None,
})
The router generates the URLs of the viewset; the whoami URL is added in front of them.
from django.urls import path
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('books', views.BookViewSet)
urlpatterns = [
path('whoami/', views.whoami, name='whoami'),
] + router.urls
The project includes the URLs of the app under /api/.
from django.urls import include, path
urlpatterns = [
path('api/', include('books.urls')),
]
The settings of DRF live in one dictionary, REST_FRAMEWORK, at the end of
config/settings.py. Instead of setting permission_classes on every view, we make
IsAuthenticatedOrReadOnly the default permission: everyone may read, only authenticated users may
write.
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
],
}
We start the development server with uv run python manage.py runserver and query the API with
curl in another terminal. Without credentials the request is anonymous. With the -u option, curl
sends the user name and password with HTTP Basic authentication, one of the two default authentication
classes. An anonymous POST is refused with the status 403.
$ curl -s localhost:8000/api/whoami/; echo
{"user":null,"authenticator":null}
$ curl -s -u alice:s3cret-alice localhost:8000/api/whoami/; echo
{"user":"alice","authenticator":"BasicAuthentication"}
$ curl -s -i localhost:8000/api/books/ -H 'Content-Type: application/json' -d '{"title": "Two Scoops of Django", "author": "Daniel Feldroy", "published": 2024, "price": "54.95"}' | sed -n '1p;$p'
HTTP/1.1 403 Forbidden
{"detail":"Authentication credentials were not provided."}
Token authentication
Basic authentication sends the password with every request, and session authentication needs cookies and a
CSRF token, which suits a browser but not a mobile app or a script. DRF's TokenAuthentication
exchanges the password once for a random token; the client then sends the token in the
Authorization header. The tokens are stored in a table of the app
rest_framework.authtoken.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'books',
]
The setting DEFAULT_AUTHENTICATION_CLASSES replaces the default classes. DRF tries them in order
until one recognizes the user. We keep the session authentication, so that the browsable API still works after
logging in.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
],
}
The new app has its own migrations.
$ uv run python manage.py migrate authtoken Operations to perform: Apply all migrations: authtoken Running migrations: Applying authtoken.0001_initial... OK Applying authtoken.0002_auto_20160226_1747... OK Applying authtoken.0003_tokenproxy... OK Applying authtoken.0004_alter_tokenproxy_options... OK
Obtaining a token
The view obtain_auth_token accepts a user name and a password and returns the user's token,
creating it on the first request.
from django.urls import include, path
from rest_framework.authtoken.views import obtain_auth_token
urlpatterns = [
path('api/', include('books.urls')),
path('api/token/', obtain_auth_token, name='api-token'),
]
After a restart of the server, alice asks for her token, and the shell stores it in a variable. The token in
the Authorization: Token ... header identifies her, and the book she creates gets her as the
owner. The token does not expire. The anonymous POST is now answered with 401 and a
WWW-Authenticate header: DRF uses the header of the first authentication class, and session
authentication has none, so the defaults gave 403. An unknown token is an error, not an anonymous request.
$ curl -s localhost:8000/api/token/ -d username=alice -d password=s3cret-alice; echo
{"token":"fe756f325789a8a10f89263a70da5018f931de04"}
$ TOKEN=$(curl -s localhost:8000/api/token/ -d username=alice -d password=s3cret-alice | jq -r .token)
$ curl -s -H "Authorization: Token $TOKEN" localhost:8000/api/whoami/; echo
{"user":"alice","authenticator":"TokenAuthentication"}
$ curl -s localhost:8000/api/books/ -H "Authorization: Token $TOKEN" -H 'Content-Type: application/json' -d '{"title": "Two Scoops of Django", "author": "Daniel Feldroy", "published": 2024, "price": "54.95"}'; echo
{"id":25,"title":"Two Scoops of Django","author":"Daniel Feldroy","published":2024,"price":"54.95","owner":"alice"}
$ curl -s -i localhost:8000/api/books/ -H 'Content-Type: application/json' -d '{"title": "Two Scoops of Django", "author": "Daniel Feldroy", "published": 2024, "price": "54.95"}' | grep -E '^(HTTP|WWW)|detail'
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Token
{"detail":"Authentication credentials were not provided."}
$ curl -s -H 'Authorization: Token 0123456789abcdef' localhost:8000/api/whoami/; echo
{"detail":"Invalid token."}
Managing tokens on the command line
An administrator can also create tokens on the command line. The command drf_create_token returns
the existing token of a user, and the -r option replaces it with a new one, which makes the old
token invalid. That is the only way to revoke a token of a user who has lost it.
$ uv run python manage.py drf_create_token bob Generated token f989d85167035b5da6978a7bf9cb641b82843d6b for user bob $ uv run python manage.py drf_create_token bob Generated token f989d85167035b5da6978a7bf9cb641b82843d6b for user bob $ uv run python manage.py drf_create_token -r bob Generated token c9f6dc4b3e54d00f341dece912daa5f757bd39dc for user bob
JSON Web Tokens
DRF tokens never expire and need a database query for every request. A JSON Web Token (JWT) carries the user
id and an expiry time and is signed with the SECRET_KEY, so the server only checks the signature.
Simple JWT issues two tokens: a short-lived access token for requests and a longer-lived refresh token for
getting new access tokens. We install the package; it brings PyJWT as a dependency.
$ uv add djangorestframework-simplejwt
JWTAuthentication replaces TokenAuthentication; the authtoken app can
stay installed. The SIMPLE_JWT dictionary sets the lifetimes of the tokens: five minutes for an
access token, one day for a refresh token.
from datetime import timedelta
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
],
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}
TokenObtainPairView checks the user name and the password and returns both tokens;
TokenRefreshView returns a new access token for a valid refresh token. Simple JWT needs no entry
in INSTALLED_APPS and no migrations.
from django.urls import include, path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
urlpatterns = [
path('api/', include('books.urls')),
path('api/jwt/', TokenObtainPairView.as_view(), name='jwt-obtain'),
path('api/jwt/refresh/', TokenRefreshView.as_view(), name='jwt-refresh'),
]
Bob logs in; the jq filter shortens the two long tokens. The access token goes in an
Authorization: Bearer ... header, and bob uses it to delete the book alice created, which the
default permission allows to any authenticated user. The refresh request returns only a new access token. A
token with a changed signature, made by appending a character, is rejected with 401, and the body of the error
names the reason. A wrong password gives a generic message that does not reveal whether the user exists.
$ curl -s localhost:8000/api/jwt/ -d username=bob -d password=s3cret-bob | jq -c 'map_values(.[:24] + "...")'
{"refresh":"eyJhbGciOiJIUzI1NiIsInR5...","access":"eyJhbGciOiJIUzI1NiIsInR5..."}
$ PAIR=$(curl -s localhost:8000/api/jwt/ -d username=bob -d password=s3cret-bob)
$ ACCESS=$(echo "$PAIR" | jq -r .access)
$ REFRESH=$(echo "$PAIR" | jq -r .refresh)
$ curl -s -H "Authorization: Bearer $ACCESS" localhost:8000/api/whoami/; echo
{"user":"bob","authenticator":"JWTAuthentication"}
$ curl -s -X DELETE -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $ACCESS" localhost:8000/api/books/25/
204
$ curl -s localhost:8000/api/jwt/refresh/ -d refresh=$REFRESH | jq 'keys'
[
"access"
]
$ curl -s -i -H "Authorization: Bearer ${ACCESS}x" localhost:8000/api/whoami/ | grep -E '^(HTTP|WWW)'
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
$ ACCESS=$(curl -s localhost:8000/api/jwt/ -d username=bob -d password=s3cret-bob | jq -r .access)
$ curl -s -H "Authorization: Bearer ${ACCESS}x" localhost:8000/api/whoami/ | jq .
{
"detail": "Given token not valid for any token type",
"code": "token_not_valid",
"messages": [
{
"token_class": "AccessToken",
"token_type": "access",
"message": "Token is invalid"
}
]
}
$ curl -s localhost:8000/api/jwt/ -d username=bob -d password=wrong; echo
{"detail":"No active account found with the given credentials"}
Inside a JWT
A JWT is not encrypted: its payload is Base64-encoded JSON that anyone can read, so it must not carry secrets. The demo creates a token pair for bob in Python, prints the claims of the access token, checks the token, and then moves its expiry time into the past.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from datetime import timedelta
from django.contrib.auth.models import User
from rest_framework_simplejwt.exceptions import TokenError
from rest_framework_simplejwt.tokens import AccessToken, RefreshToken
bob = User.objects.get(username='bob')
refresh = RefreshToken.for_user(bob)
access = refresh.access_token
for name, value in access.payload.items():
print(f'{name:10} {value}')
print('lifetime:', access['exp'] - access['iat'], 's')
print('valid:', AccessToken(str(access))['user_id'])
access.set_exp(lifetime=timedelta(seconds=-1))
try:
AccessToken(str(access))
except TokenError as error:
print('error:', error)
The claims are the token type, the expiry and issue times as Unix timestamps, a unique token id
jti, and the user id. The access token lives 300 seconds, as configured. Constructing an
AccessToken from a string verifies the signature and the expiry time, and raises
TokenError for an expired token. Because a JWT is checked without the database, a stolen access
token works until it expires; this is why its lifetime is short.
$ uv run python -m demos.tokens token_type access exp 1795375340 iat 1795375040 jti d89e7e963bc942dfb156ec64a61c42c6 user_id 2 lifetime: 300 s valid: 2 error: Token is expired
Page number pagination
The list of books grows with the database. Pagination splits it into pages. The setting
DEFAULT_PAGINATION_CLASS enables it for every list view, and PAGE_SIZE sets the
number of items on a page. The other keys of the dictionary stay as before.
REST_FRAMEWORK = {
...
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 5,
}
The list is now wrapped in an object: count is the number of all books, next and
previous are the links to the neighbouring pages, and results holds the books of the
page. The page parameter selects a page; a page past the end is answered with 404. The detail
URLs are not affected.
$ curl -s localhost:8000/api/books/ | jq -c '{count, next, previous, titles: [.results[].title]}'
{"count":24,"next":"http://localhost:8000/api/books/?page=2","previous":null,"titles":["Architecture Patterns with Python","Clean Architecture","Clean Code","Code Complete","Design Patterns"]}
$ curl -s 'localhost:8000/api/books/?page=5' | jq -c '{count, next, previous, titles: [.results[].title]}'
{"count":24,"next":null,"previous":"http://localhost:8000/api/books/?page=4","titles":["The Mythical Man-Month","The Pragmatic Programmer","Two Scoops of Django","Working Effectively with Legacy Code"]}
$ curl -s 'localhost:8000/api/books/?page=6'; echo
{"detail":"Invalid page."}
$ curl -s localhost:8000/api/books/3/; echo
{"id":3,"title":"The Clean Coder","author":"Robert C. Martin","published":2011,"price":"32.99","owner":"bob"}
A custom page size
A pagination class is configured with class attributes. A subclass of PageNumberPagination lets
the client choose the page size with the parameter size, up to max_page_size.
from rest_framework.pagination import PageNumberPagination
class BookPagination(PageNumberPagination):
page_size = 5
page_size_query_param = 'size'
max_page_size = 10
The attribute pagination_class sets the class for one view and overrides the default; the rest of
books/views.py is unchanged.
...
from .pagination import BookPagination
...
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = BookPagination
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
Eight books per page give three pages. A size above the limit is reduced to ten, and the links keep the
size parameter.
$ curl -s 'localhost:8000/api/books/?size=8&page=3' | jq -c '{count, next, previous, titles: [.results[].title]}'
{"count":24,"next":null,"previous":"http://localhost:8000/api/books/?page=2&size=8","titles":["Release It!","Serious Python","Test-Driven Development","The Clean Coder","The Mythical Man-Month","The Pragmatic Programmer","Two Scoops of Django","Working Effectively with Legacy Code"]}
$ curl -s 'localhost:8000/api/books/?size=100' | jq '.results | length'
10
$ curl -s 'localhost:8000/api/books/?size=100&page=3' | jq -c '[.next, .previous]'
[null,"http://localhost:8000/api/books/?page=2&size=100"]
Cursor pagination
Page numbers have two weaknesses. A deep page needs an OFFSET query, which the database answers
by skipping all the rows before it, and when a book is added while a client is paging, the following pages
shift and an item appears twice or not at all. CursorPagination avoids both: the link to the next
page contains an encoded position in a fixed order, and the next query continues from that position. The order
must be stable and unique, so we add the id as the second key. LimitOffsetPagination, the third
built-in class, uses the parameters limit and offset and shares the weaknesses of
page numbers.
from rest_framework.pagination import CursorPagination, PageNumberPagination
class BookPagination(PageNumberPagination):
page_size = 5
page_size_query_param = 'size'
max_page_size = 10
class LatestPagination(CursorPagination):
page_size = 4
ordering = ['-published', '-id']
A cursor suits a feed of the newest books. The generic view LatestBooks lists the books with
LatestPagination, newest first.
from rest_framework import generics, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Book
from .pagination import BookPagination, LatestPagination
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = BookPagination
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class LatestBooks(generics.ListAPIView):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = LatestPagination
@api_view(['GET'])
def whoami(request):
authenticator = request.successful_authenticator
return Response({
'user': request.user.username or None,
'authenticator': type(authenticator).__name__ if authenticator else None,
})
The new view gets the URL latest/.
from django.urls import path
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('books', views.BookViewSet)
urlpatterns = [
path('whoami/', views.whoami, name='whoami'),
path('latest/', views.LatestBooks.as_view(), name='latest'),
] + router.urls
The response has no count and no page numbers, only the links. The cursor in the link is opaque;
the client follows the links and does not build them. An invalid cursor gives 404.
$ curl -s localhost:8000/api/latest/ | jq -c '{next, previous, books: [.results[] | "\(.published) \(.title)"]}'
{"next":"http://localhost:8000/api/latest/?cursor=bz0xJnA9MjAyMg%3D%3D","previous":null,"books":["2023 Python Crash Course","2022 Python Testing with pytest","2022 Fluent Python","2020 Architecture Patterns with Python"]}
$ NEXT=$(curl -s localhost:8000/api/latest/ | jq -r .next)
$ curl -s "$NEXT" | jq -c '[.results[] | "\(.published) \(.title)"]'
["2020 Two Scoops of Django","2019 Effective Python","2018 Release It!","2018 Serious Python"]
$ curl -s 'localhost:8000/api/latest/?cursor=bogus'; echo
{"detail":"Invalid cursor"}
Filtering with django-filter
Clients often need only some of the books: those of one author or one year. The package django-filter turns
query parameters into QuerySet filters and validates them. We install it and add it to
INSTALLED_APPS; its import name is django_filters.
$ uv add django-filter
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'django_filters',
'books',
]
A filter backend narrows the QuerySet of a list view. DjangoFilterBackend with
filterset_fields creates an exact-match filter for each listed field; a field can follow
relations, as owner__username does.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Book
from .pagination import BookPagination, LatestPagination
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = BookPagination
filter_backends = [DjangoFilterBackend]
filterset_fields = ['author', 'published', 'owner__username']
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class LatestBooks(generics.ListAPIView):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = LatestPagination
@api_view(['GET'])
def whoami(request):
authenticator = request.successful_authenticator
return Response({
'user': request.user.username or None,
'authenticator': type(authenticator).__name__ if authenticator else None,
})
The filters work together with pagination: count is the number of matching books. A value that is
not a number is rejected with 400 and a message, as in a Django form. The matches are exact, so the lowercase
name finds nothing.
$ curl -s 'localhost:8000/api/books/?author=Martin+Fowler' | jq -c '.count, (.results[] | [.title, .author, .published, .price])'
2
["Patterns of Enterprise Application Architecture","Martin Fowler",2002,"59.00"]
["Refactoring","Martin Fowler",2018,"47.99"]
$ curl -s 'localhost:8000/api/books/?published=2018&owner__username=bob' | jq -c '.count, (.results[] | [.title, .author, .published, .price])'
3
["Refactoring","Martin Fowler",2018,"47.99"]
["Release It!","Michael T. Nygard",2018,"42.95"]
["Serious Python","Julien Danjou",2018,"29.95"]
$ curl -s 'localhost:8000/api/books/?published=old'; echo
{"published":["Enter a number."]}
$ curl -s 'localhost:8000/api/books/?author=martin+fowler' | jq .count
0
A custom FilterSet
For other lookups we declare a FilterSet, a class similar to a Django form. Each filter names the
model field and the lookup. The parameter names need not match the fields: min_price and
max_price both filter the price, and owner follows the relation to the user.
import django_filters
from .models import Book
class BookFilter(django_filters.FilterSet):
author = django_filters.CharFilter(lookup_expr='icontains')
min_price = django_filters.NumberFilter(field_name='price', lookup_expr='gte')
max_price = django_filters.NumberFilter(field_name='price', lookup_expr='lte')
since = django_filters.NumberFilter(field_name='published', lookup_expr='gte')
owner = django_filters.CharFilter(field_name='owner__username')
class Meta:
model = Book
fields = ['author', 'min_price', 'max_price', 'since', 'owner']
The viewset uses the class with filterset_class instead of filterset_fields. Only
the viewset changes, and the import from .filters import BookFilter is added.
...
from .filters import BookFilter
...
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = BookPagination
filter_backends = [DjangoFilterBackend]
filterset_class = BookFilter
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
The author filter now matches a part of the name in any case: six books, of which the first page
shows five. Several filters are combined with AND.
$ curl -s 'localhost:8000/api/books/?author=martin' | jq -c '.count, (.results[] | [.title, .author, .published, .price])'
6
["Clean Architecture","Robert C. Martin",2017,"36.99"]
["Clean Code","Robert C. Martin",2008,"37.50"]
["Designing Data-Intensive Applications","Martin Kleppmann",2017,"49.99"]
["Patterns of Enterprise Application Architecture","Martin Fowler",2002,"59.00"]
["Refactoring","Martin Fowler",2018,"47.99"]
$ curl -s 'localhost:8000/api/books/?min_price=40&max_price=50&since=2015' | jq -c '.count, (.results[] | [.title, .author, .published, .price])'
5
["Architecture Patterns with Python","Harry Percival",2020,"45.99"]
["Designing Data-Intensive Applications","Martin Kleppmann",2017,"49.99"]
["Refactoring","Martin Fowler",2018,"47.99"]
["Release It!","Michael T. Nygard",2018,"42.95"]
["Two Scoops of Django","Daniel Feldroy",2020,"49.95"]
$ curl -s 'localhost:8000/api/books/?owner=alice&max_price=35' | jq -c '.count, [.results[].title]'
2
["Programming Pearls","The Mythical Man-Month"]
$ curl -s 'localhost:8000/api/books/?min_price=cheap'; echo
{"min_price":["Enter a number."]}
Search and ordering
DRF has two more filter backends. SearchFilter reads the parameter search and looks
up each of its words in the search_fields with icontains.
OrderingFilter sorts by the parameter ordering, but only by the fields listed in
ordering_fields; without the list a client could sort by any field, including those not shown in
the API. The listing is the final version of the views module.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters, generics, viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .filters import BookFilter
from .models import Book
from .pagination import BookPagination, LatestPagination
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = BookPagination
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
filterset_class = BookFilter
search_fields = ['title', 'author']
ordering_fields = ['title', 'published', 'price']
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class LatestBooks(generics.ListAPIView):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
pagination_class = LatestPagination
@api_view(['GET'])
def whoami(request):
authenticator = request.successful_authenticator
return Response({
'user': request.user.username or None,
'authenticator': type(authenticator).__name__ if authenticator else None,
})
A book matches a search when every word occurs in at least one of the fields: "clean martin" finds the three books whose title contains "clean" and whose author is Robert C. Martin. A minus sign reverses the order, and a comma separates several keys. All the backends combine with each other and with pagination. Ordering by a field that is not allowed is silently ignored.
$ curl -s 'localhost:8000/api/books/?search=python' | jq -c '.count, (.results[] | [.title, .author, .published, .price])' 7 ["Architecture Patterns with Python","Harry Percival",2020,"45.99"] ["Effective Python","Brett Slatkin",2019,"39.99"] ["Fluent Python","Luciano Ramalho",2022,"59.99"] ["Python Cookbook","David Beazley",2013,"49.99"] ["Python Crash Course","Eric Matthes",2023,"34.99"] $ curl -s 'localhost:8000/api/books/?search=clean+martin' | jq -c '.count, (.results[] | [.title, .author, .published, .price])' 3 ["Clean Architecture","Robert C. Martin",2017,"36.99"] ["Clean Code","Robert C. Martin",2008,"37.50"] ["The Clean Coder","Robert C. Martin",2011,"32.99"] $ curl -s 'localhost:8000/api/books/?ordering=-price&size=3' | jq -c '.count, (.results[] | [.title, .author, .published, .price])' 24 ["Introduction to Algorithms","Thomas H. Cormen",2009,"89.99"] ["Domain-Driven Design","Eric Evans",2003,"64.99"] ["Fluent Python","Luciano Ramalho",2022,"59.99"] $ curl -s 'localhost:8000/api/books/?search=python&ordering=-published,title&since=2020' | jq -c '.count, (.results[] | [.title, .author, .published, .price])' 4 ["Python Crash Course","Eric Matthes",2023,"34.99"] ["Fluent Python","Luciano Ramalho",2022,"59.99"] ["Python Testing with pytest","Brian Okken",2022,"39.95"] ["Architecture Patterns with Python","Harry Percival",2020,"45.99"] $ curl -s 'localhost:8000/api/books/?ordering=owner' | jq -r '.results[0].title' Architecture Patterns with Python
Throttling
Throttling limits the number of requests a client may make in a period, which protects the server from scripts
that send too many requests. AnonRateThrottle counts the requests of anonymous clients by their
IP address, UserRateThrottle those of authenticated users by the user id. The rates are given as
a number of requests per second, minute, hour, or day.
REST_FRAMEWORK = {
...
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '5/minute',
'user': '100/minute',
},
}
The throttles keep their counters in Django's cache, the default local-memory cache here. That cache belongs
to one process, so with several worker processes each has its own counters; a production server needs a shared
cache such as Redis (see Django caching). The client's address comes from
REMOTE_ADDR, which behind a proxy is the proxy's address; the setting NUM_PROXIES
makes DRF read X-Forwarded-For instead. Throttling is therefore a protection against overuse, not
a security barrier.
After the restart, bob logs in, and then we send seven anonymous requests. Only four succeed: the login
request was anonymous as well and counted as the first of five. A throttled request gets the status 429 and
the header Retry-After with the number of seconds to wait. Bob's authenticated requests are
counted separately against the higher user rate.
$ ACCESS=$(curl -s localhost:8000/api/jwt/ -d username=bob -d password=s3cret-bob | jq -r .access)
$ for i in $(seq 7); do curl -s -o /dev/null -w '%{http_code} ' localhost:8000/api/whoami/; done; echo
200 200 200 200 429 429 429
$ curl -s -i localhost:8000/api/whoami/ | grep -E '^(HTTP|Retry-After)|detail'
HTTP/1.1 429 Too Many Requests
Retry-After: 60
{"detail":"Request was throttled. Expected available in 60 seconds."}
$ for i in $(seq 7); do curl -s -o /dev/null -w '%{http_code} ' -H "Authorization: Bearer $ACCESS" localhost:8000/api/whoami/; done; echo
200 200 200 200 200 200 200
A stricter limit for logging in
The login view accepts passwords, so it deserves a lower limit than the rest of the API, to slow down
guessing. ScopedRateThrottle applies the rate of the scope named by the view's
throttle_scope. The view below subclasses TokenObtainPairView and replaces its
throttles with the scoped one.
from rest_framework.throttling import ScopedRateThrottle
from rest_framework_simplejwt.views import TokenObtainPairView
class LoginView(TokenObtainPairView):
throttle_classes = [ScopedRateThrottle]
throttle_scope = 'login'
The new view takes the place of TokenObtainPairView in the URLs.
from django.urls import include, path
from rest_framework_simplejwt.views import TokenRefreshView
from books.auth_views import LoginView
urlpatterns = [
path('api/', include('books.urls')),
path('api/jwt/', LoginView.as_view(), name='jwt-obtain'),
path('api/jwt/refresh/', TokenRefreshView.as_view(), name='jwt-refresh'),
]
The rate of the scope login is added to DEFAULT_THROTTLE_RATES. The listing shows
the final part of config/settings.py, from the import of timedelta, which we put
above the dictionary.
from datetime import timedelta
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
'rest_framework.authentication.SessionAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticatedOrReadOnly',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 5,
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle',
],
'DEFAULT_THROTTLE_RATES': {
'anon': '5/minute',
'user': '100/minute',
'login': '3/minute',
},
}
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
}
Three wrong passwords are allowed, the fourth attempt is throttled, and so is the correct password for the
rest of the minute. The other views keep their own limits; the anonymous request to whoami still
succeeds.
$ for i in $(seq 4); do curl -s localhost:8000/api/jwt/ -d username=alice -d password=guess$i; echo; done
{"detail":"No active account found with the given credentials"}
{"detail":"No active account found with the given credentials"}
{"detail":"No active account found with the given credentials"}
{"detail":"Request was throttled. Expected available in 60 seconds."}
$ curl -s localhost:8000/api/jwt/ -d username=alice -d password=s3cret-alice | jq -c 'keys'
["detail"]
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/api/whoami/
200
Testing the API
APITestCase provides DRF's test client. Its credentials() method sets headers for
all following requests, which is how a test logs in with a real JWT. The tests create twelve books with prices
from 10 to 21. The method setUp() clears the cache before each test: the throttles keep their
counters there, and the cache is not reset between tests.
from django.contrib.auth.models import User
from django.core.cache import cache
from rest_framework import status
from rest_framework.test import APITestCase
from .models import Book
class BookApiTests(APITestCase):
@classmethod
def setUpTestData(cls):
cls.alice = User.objects.create_user('alice', password='s3cret-alice')
Book.objects.bulk_create(
Book(title=f'Book {n:02}', author='Ann Writer', published=2000 + n,
price=10 + n, owner=cls.alice)
for n in range(12)
)
def setUp(self):
cache.clear()
def login(self):
data = {'username': 'alice', 'password': 's3cret-alice'}
response = self.client.post('/api/jwt/', data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + response.data['access'])
def test_jwt_login(self):
self.login()
response = self.client.get('/api/whoami/')
self.assertEqual(response.data['user'], 'alice')
def test_anonymous_post_is_refused(self):
response = self.client.post('/api/books/', {'title': 'X'}, format='json')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_pagination(self):
response = self.client.get('/api/books/', {'size': 4, 'page': 3})
self.assertEqual(response.data['count'], 12)
self.assertIsNone(response.data['next'])
self.assertEqual(len(response.data['results']), 4)
def test_filter_and_ordering(self):
query = {'min_price': 15, 'ordering': '-price'}
response = self.client.get('/api/books/', query)
prices = [book['price'] for book in response.data['results']]
self.assertEqual(prices, ['21.00', '20.00', '19.00', '18.00', '17.00'])
def test_anonymous_throttle(self):
for _ in range(5):
self.client.get('/api/whoami/')
response = self.client.get('/api/whoami/')
self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
The tests check the login with a JWT, the 401 response for an anonymous POST, the page size and the last page, a filter combined with ordering, and the anonymous throttle.
$ uv run python manage.py test Found 5 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). ..... ---------------------------------------------------------------------- Ran 5 tests in 0.465s OK Destroying test database for alias 'default'...
Throttle counters between tests
The test database is rolled back after each test, but the cache is not. Without cache.clear(),
the six anonymous requests of the throttle test use up the limit, and the tests that run after it in
alphabetical order get 429 responses, which have no count or results keys.
$ uv run python manage.py test | grep -E "^(FAIL|ERROR|KeyError|Ran|FAILED|OK)" ERROR: test_filter_and_ordering (books.tests.BookApiTests.test_filter_and_ordering) KeyError: 'results' ERROR: test_pagination (books.tests.BookApiTests.test_pagination) KeyError: 'count' Ran 5 tests in 0.457s FAILED (errors=2)
Source
Django REST framework: Authentication
Django REST framework: Pagination
Django REST framework: Filtering
Django REST framework: Throttling
In this article we have authenticated API clients with DRF tokens and with JSON Web Tokens from Simple JWT, split lists into pages with page numbers and cursors, filtered them with django-filter, added search and ordering, limited the request rate with throttles, and tested these features. Related articles are Django REST framework, Django authentication, Django pagination, and Django testing.
Author
List all Django tutorials.