Django REST framework
last modified November 21, 2026 Python 3.15
Django REST framework (DRF) is a third-party package for building web APIs with Django. Django alone can return JSON with JsonResponse, but then we convert models to dictionaries, parse and validate the request body, and choose the status codes ourselves. DRF does this work: serializers convert model instances to JSON and validate incoming data, API views handle content negotiation and errors, viewsets and routers generate the URLs of a whole resource, and permissions decide who may change what. In this article we build a small API for books step by step, from a serializer used in a script to a viewset with permissions and tests. The examples use Django 6.1, Django REST framework 3.18, 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.
$ 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 instead of one level deeper. The package djangorestframework is imported as rest_framework. Both
rest_framework, which provides the templates of the browsable API, 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.
The API serves books. A book has a title, an author, the year of publication, and a price.
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)
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
The script seed.py fills the table with four books. It deletes the old rows first, so it can be run again.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from books.models import Book
Book.objects.all().delete()
Book.objects.bulk_create([
Book(title='Clean Code', author='Robert C. Martin', published=2008, price='37.50'),
Book(title='Fluent Python', author='Luciano Ramalho', published=2022, price='59.99'),
Book(title='Refactoring', author='Martin Fowler', published=2018, price='47.99'),
Book(title='The Pragmatic Programmer', author='Andrew Hunt', published=1999, price='41.99'),
])
for book in Book.objects.all():
print(book.pk, book.title, book.published, book.price)
The books get the ids 1 to 4.
$ uv run python -m demos.seed 1 Clean Code 2008 37.50 2 Fluent Python 2022 59.99 3 Refactoring 2018 47.99 4 The Pragmatic Programmer 1999 41.99
A first serializer
A serializer declares the fields of the representation, much like a Django form declares the fields of an HTML form. The class
Serializer knows nothing about models; each field has a type and options. The field id is
read_only: it appears in the output but is never accepted in input.
from rest_framework import serializers
class BookSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(max_length=100)
author = serializers.CharField(max_length=60)
published = serializers.IntegerField(min_value=0)
price = serializers.DecimalField(max_digits=6, decimal_places=2)
Passing an instance to the serializer and reading its data attribute turns the book into a dictionary of Python primitives.
JSONRenderer renders that dictionary as JSON bytes, which is what an API view will send. With many=True the
serializer handles a list or a QuerySet.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from rest_framework.renderers import JSONRenderer
from books.models import Book
from books.serializers import BookSerializer
book = Book.objects.get(title='Fluent Python')
serializer = BookSerializer(book)
print(serializer.data)
print(JSONRenderer().render(serializer.data))
serializer = BookSerializer(Book.objects.all()[:2], many=True)
for item in serializer.data:
print(item['title'], item['price'])
The price is a string. DRF renders decimals as strings by default, so that a client parsing the JSON into floats does not lose the
exact value; the setting COERCE_DECIMAL_TO_STRING changes it.
$ uv run python -m demos.serialize
{'id': 2, 'title': 'Fluent Python', 'author': 'Luciano Ramalho', 'published': 2022, 'price': '59.99'}
b'{"id":2,"title":"Fluent Python","author":"Luciano Ramalho","published":2022,"price":"59.99"}'
Clean Code 37.50
Fluent Python 59.99
Validating and saving data
The other direction starts with data=. The serializer validates the input and puts the converted values into
validated_data; its save() method calls create() or, when the serializer was also given an
instance, update(). A plain Serializer does not know how to store a book, so we write both methods.
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
title = serializers.CharField(max_length=100)
author = serializers.CharField(max_length=60)
published = serializers.IntegerField(min_value=0)
price = serializers.DecimalField(max_digits=6, decimal_places=2)
def create(self, validated_data):
return Book.objects.create(**validated_data)
def update(self, instance, validated_data):
for field, value in validated_data.items():
setattr(instance, field, value)
instance.save()
return instance
The demo creates a book, changes its price with a partial update, and then tries invalid data. partial=True makes all
fields optional, so the update can send only the price. is_valid(raise_exception=True) raises a
ValidationError instead of returning False; the API views rely on it later.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from books.models import Book
from books.serializers import BookSerializer
data = {'title': 'Two Scoops of Django', 'author': 'Daniel Feldroy',
'published': 2020, 'price': '49.95'}
serializer = BookSerializer(data=data)
print('valid:', serializer.is_valid())
print(serializer.validated_data)
book = serializer.save()
print('created:', book.pk, book.title)
serializer = BookSerializer(book, data={'price': '44.95'}, partial=True)
serializer.is_valid(raise_exception=True)
print('updated:', serializer.save().price)
bad = BookSerializer(data={'title': 'Untitled', 'published': -5, 'price': 'cheap'})
print('valid:', bad.is_valid())
for field, errors in bad.errors.items():
print(field, errors)
book.delete()
print('books:', Book.objects.count())
The validated price is a Decimal. The invalid data produces one list of errors per field, each with a message and a
code. The script deletes the new book at the end, but SQLite does not reuse its id.
$ uv run python -m demos.deserialize
valid: True
{'title': 'Two Scoops of Django', 'author': 'Daniel Feldroy', 'published': 2020, 'price': Decimal('49.95')}
created: 5 Two Scoops of Django
updated: 44.95
valid: False
author [ErrorDetail(string='This field is required.', code='required')]
published [ErrorDetail(string='Ensure this value is greater than or equal to 0.', code='min_value')]
price [ErrorDetail(string='A valid number is required.', code='invalid')]
books: 4
ModelSerializer and custom validation
Most serializers mirror a model. ModelSerializer generates the fields from the model, together with their validators, and
provides create() and update(). The list fields in Meta chooses the fields; listing
them explicitly is safer than '__all__', which would expose every future column. A method validate_<field>
checks one field, and validate() checks the fields together; both raise serializers.ValidationError.
from datetime import date
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['id', 'title', 'author', 'published', 'price']
def validate_published(self, value):
if value > date.today().year:
raise serializers.ValidationError('The year cannot be in the future.')
return value
def validate(self, data):
if 'Django' in data.get('title', '') and data.get('published', 2005) < 2005:
raise serializers.ValidationError('Django was released in 2005.')
return data
The repr() of a ModelSerializer shows the generated fields, which is useful when a field does not behave as
expected. The demo then validates three invalid books.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from books.serializers import BookSerializer
print(repr(BookSerializer()))
samples = [
{'title': 'Future Book', 'author': 'Nobody', 'published': 2099, 'price': '10.00'},
{'title': 'Early Django', 'author': 'Nobody', 'published': 1999, 'price': '10.00'},
{'title': 'A' * 120, 'author': 'Nobody', 'published': 2020, 'price': '1234567'},
]
for data in samples:
serializer = BookSerializer(data=data)
serializer.is_valid()
print(dict(serializer.errors))
The id is read-only because it is the primary key. The limits come from the model: the length of the char fields, the digits
of the price, and the range of the integer field as reported by the SQLite backend. The error of validate() is stored under
the key non_field_errors.
$ uv run python -m demos.modelser
BookSerializer():
id = BigIntegerField(label='ID', read_only=True)
title = CharField(max_length=100)
author = CharField(max_length=60)
published = IntegerField(max_value=9223372036854775807, min_value=0)
price = DecimalField(decimal_places=2, max_digits=6)
{'published': [ErrorDetail(string='The year cannot be in the future.', code='invalid')]}
{'non_field_errors': [ErrorDetail(string='Django was released in 2005.', code='invalid')]}
{'title': [ErrorDetail(string='Ensure this field has no more than 100 characters.', code='max_length')], 'price': [ErrorDetail(string='Ensure that there are no more than 6 digits in total.', code='max_digits')]}
Function-based API views
The decorator @api_view turns a function into an API view. The request is a DRF Request, whose
data attribute holds the parsed body for JSON as well as for form data, and the view returns a Response with
Python data, which DRF renders in the format the client asked for. Methods not listed in the decorator are answered with 405. A
ValidationError from is_valid(raise_exception=True) becomes a 400 response with the errors, and the
Http404 raised by get_object_or_404 a 404 response with a JSON message.
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer
@api_view(['GET', 'POST'])
def book_list(request):
if request.method == 'POST':
serializer = BookSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
serializer = BookSerializer(Book.objects.all(), many=True)
return Response(serializer.data)
@api_view(['GET', 'PUT', 'PATCH', 'DELETE'])
def book_detail(request, pk):
book = get_object_or_404(Book, pk=pk)
if request.method == 'GET':
return Response(BookSerializer(book).data)
if request.method == 'DELETE':
book.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
partial = request.method == 'PATCH'
serializer = BookSerializer(book, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
The URL configuration of the app has one URL for the collection and one for a single book.
from django.urls import path
from . import views
urlpatterns = [
path('books/', views.book_list, name='book-list'),
path('books/<int:pk>/', views.book_detail, name='book-detail'),
]
The project includes the URLs of the app under /api/.
from django.urls import include, path
urlpatterns = [
path('api/', include('books.urls')),
]
We start the development server.
$ uv run python manage.py runserver
With curl we list the books and read one of them. The tool jq prints each book of the list on its own line.
$ curl -s localhost:8000/api/books/ | jq -c '.[]'
{"id":1,"title":"Clean Code","author":"Robert C. Martin","published":2008,"price":"37.50"}
{"id":2,"title":"Fluent Python","author":"Luciano Ramalho","published":2022,"price":"59.99"}
{"id":3,"title":"Refactoring","author":"Martin Fowler","published":2018,"price":"47.99"}
{"id":4,"title":"The Pragmatic Programmer","author":"Andrew Hunt","published":1999,"price":"41.99"}
$ curl -s localhost:8000/api/books/2/
{"id":2,"title":"Fluent Python","author":"Luciano Ramalho","published":2022,"price":"59.99"}
Creating, updating, and deleting
A POST to the collection creates a book and returns it with the status 201; the sed command keeps only the status line and the
body. Missing fields give a 400 response with the errors from the serializer. Since @api_view exempts the view from the CSRF
check for requests without a session, curl needs no token.
$ curl -s -i localhost:8000/api/books/ -H 'Content-Type: application/json' -d '{"title": "Two Scoops of Django", "author": "Daniel Feldroy", "published": 2020, "price": "49.95"}' | sed -n '1p;$p'
HTTP/1.1 201 Created
{"id":6,"title":"Two Scoops of Django","author":"Daniel Feldroy","published":2020,"price":"49.95"}
$ curl -s localhost:8000/api/books/ -H 'Content-Type: application/json' -d '{"title": "Early Django", "published": 1999}'; echo
{"author":["This field is required."],"price":["This field is required."]}
PATCH changes only the price, DELETE answers 204 without a body, and the deleted book is gone. A body in a format that no parser understands is rejected with 415. The default parsers accept JSON, form data, and multipart data.
$ curl -s -X PATCH localhost:8000/api/books/6/ -H 'Content-Type: application/json' -d '{"price": "44.95"}'; echo
{"id":6,"title":"Two Scoops of Django","author":"Daniel Feldroy","published":2020,"price":"44.95"}
$ curl -s -o /dev/null -w '%{http_code}\n' -X DELETE localhost:8000/api/books/6/
204
$ curl -s localhost:8000/api/books/6/; echo
{"detail":"No Book matches the given query."}
$ curl -s -X PUT localhost:8000/api/books/2/ -H 'Content-Type: text/plain' -d 'price=1'; echo
{"detail":"Unsupported media type \"text/plain\" in request."}
Content negotiation
DRF chooses the renderer from the Accept header. curl sends */* and gets JSON, while a browser asks for
text/html and gets the browsable API, which we look at later. The query parameter format picks the renderer
explicitly. The form parser makes the same view work for an ordinary form-encoded POST; the last command removes the book again.
$ curl -s -o /dev/null -w '%{content_type}\n' localhost:8000/api/books/
application/json
$ curl -s -o /dev/null -w '%{content_type}\n' -H 'Accept: text/html' localhost:8000/api/books/
text/html; charset=utf-8
$ curl -s 'localhost:8000/api/books/?format=json' | head -c 80; echo
[{"id":1,"title":"Clean Code","author":"Robert C. Martin","published":2008,"pric
$ curl -s -X POST localhost:8000/api/books/ -d 'title=Clean Architecture&author=Robert C. Martin&published=2017&price=36.99'; echo
{"id":7,"title":"Clean Architecture","author":"Robert C. Martin","published":2017,"price":"36.99"}
$ curl -s -o /dev/null -w '%{http_code}\n' -X DELETE localhost:8000/api/books/7/
204
Class-based APIView
APIView is the class-based variant: one method per HTTP verb, like Django's View (see
Django class-based views). It also lets us share code between methods; here put() and
patch() call the same helper.
from rest_framework import status
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Book
from .serializers import BookSerializer
class BookList(APIView):
def get(self, request):
serializer = BookSerializer(Book.objects.all(), many=True)
return Response(serializer.data)
def post(self, request):
serializer = BookSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
class BookDetail(APIView):
def get(self, request, pk):
book = get_object_or_404(Book, pk=pk)
return Response(BookSerializer(book).data)
def put(self, request, pk):
return self.save(request, pk, partial=False)
def patch(self, request, pk):
return self.save(request, pk, partial=True)
def delete(self, request, pk):
get_object_or_404(Book, pk=pk).delete()
return Response(status=status.HTTP_204_NO_CONTENT)
def save(self, request, pk, partial):
book = get_object_or_404(Book, pk=pk)
serializer = BookSerializer(book, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
The URLs now point to as_view() of the classes.
from django.urls import path
from . import views
urlpatterns = [
path('books/', views.BookList.as_view(), name='book-list'),
path('books/<int:pk>/', views.BookDetail.as_view(), name='book-detail'),
]
The Allow header lists the methods the class defines, together with HEAD and OPTIONS, which DRF adds. The validation from
validate_published() applies in the API as well.
$ curl -s -i -X OPTIONS localhost:8000/api/books/1/ | grep -i '^allow'
Allow: GET, PUT, PATCH, DELETE, HEAD, OPTIONS
$ curl -s -X DELETE localhost:8000/api/books/; echo
{"detail":"Method \"DELETE\" not allowed."}
$ curl -s -X PATCH localhost:8000/api/books/1/ -H 'Content-Type: application/json' -d '{"published": 2099}'; echo
{"published":["The year cannot be in the future."]}
Generic views
The two classes repeat what almost every API does. DRF's generic views put that code into mixins: ListCreateAPIView lists
and creates, RetrieveUpdateDestroyAPIView reads, updates, and deletes one object, looked up by the URL argument
pk. We only say which QuerySet and which serializer to use. The URLs stay the same.
from rest_framework import generics
from .models import Book
from .serializers import BookSerializer
class BookList(generics.ListCreateAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
class BookDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
The API behaves as before.
$ curl -s localhost:8000/api/books/ | jq -c '.[] | [.id, .title]'
[1,"Clean Code"]
[2,"Fluent Python"]
[3,"Refactoring"]
[4,"The Pragmatic Programmer"]
$ curl -s localhost:8000/api/books/99/; echo
{"detail":"No Book matches the given query."}
$ curl -s -X PATCH localhost:8000/api/books/1/ -H 'Content-Type: application/json' -d '{"price": "39.00"}'; echo
{"id":1,"title":"Clean Code","author":"Robert C. Martin","published":2008,"price":"39.00"}
Viewsets and routers
A viewset goes one step further and handles both URLs of a resource in one class. ModelViewSet has the actions
list, create, retrieve, update, partial_update, and
destroy.
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
A router creates the URL patterns for registered viewsets. DefaultRouter also adds an API root view that lists the
resources, and URLs with format suffixes such as .json. The names of the routes come from the model:
book-list and book-detail.
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register('books', views.BookViewSet)
urlpatterns = router.urls
The demo prints the patterns of the router.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from books.urls import router
for url in router.urls:
print(f'{url.name:18} {url.pattern}')
Each route exists with and without the format suffix. The empty pattern is the API root.
$ uv run python -m demos.routes book-list ^books/$ book-list ^books\.(?P<format>[a-z0-9]+)/?$ book-detail ^books/(?P<pk>[^/.]+)/$ book-detail ^books/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ api-root api-root <drf_format_suffix:format>
The root returns links to the resources, and a suffix selects the format just like the parameter format.
$ curl -s localhost:8000/api/; echo
{"books":"http://localhost:8000/api/books/"}
$ curl -s localhost:8000/api/books/4/; echo
{"id":4,"title":"The Pragmatic Programmer","author":"Andrew Hunt","published":1999,"price":"41.99"}
$ curl -s localhost:8000/api/books/4.json; echo
{"id":4,"title":"The Pragmatic Programmer","author":"Andrew Hunt","published":1999,"price":"41.99"}
The browsable API
Opening http://127.0.0.1:8000/api/books/ in a browser shows the browsable API: the same data, rendered as HTML with the
headers of the response, links between the resources, and forms for the allowed methods. It makes an API easy to explore and test by hand.
The breadcrumbs lead to the API root.
Adding an owner
So far anyone can change any book. To restrict that, every book gets an owner: a foreign key to the user model. The field is nullable, so that the migration can add it to the existing rows.
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,
null=True, related_name='books')
class Meta:
ordering = ['title']
def __str__(self):
return self.title
We create and apply the migration.
$ uv run python manage.py makemigrations books
Migrations for 'books':
books/migrations/0002_book_owner.py
+ Add field owner to book
$ uv run python manage.py migrate books | tail -n 1
Applying books.0002_book_owner... OK
The script owners.py creates the users alice and bob and gives them the books: the older ones to alice, the newer ones to bob.
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
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.filter(published__lt=2010).update(owner=alice)
Book.objects.filter(published__gte=2010).update(owner=bob)
for book in Book.objects.select_related('owner'):
print(book.pk, book.title, book.owner.username)
Each book now has an owner.
$ uv run python -m demos.owners 1 Clean Code alice 2 Fluent Python bob 3 Refactoring bob 4 The Pragmatic Programmer alice
Authentication and permissions
The serializer shows the owner's user name. ReadOnlyField with source='owner.username' follows the relation, and
because it is read-only, a client cannot set the owner.
from datetime import date
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']
def validate_published(self, value):
if value > date.today().year:
raise serializers.ValidationError('The year cannot be in the future.')
return value
def validate(self, data):
if 'Django' in data.get('title', '') and data.get('published', 2005) < 2005:
raise serializers.ValidationError('Django was released in 2005.')
return data
The viewset sets permission_classes. IsAuthenticatedOrReadOnly lets everyone read, but only authenticated users
write. The hook perform_create() saves the new book with the user of the request as the owner. The QuerySet uses
select_related, so the list does not run a query per book for the owner (see
Django query performance).
from rest_framework import permissions, viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
The URLs api-auth/ add the login and logout views of the browsable API.
from django.urls import include, path
urlpatterns = [
path('api/', include('books.urls')),
path('api-auth/', include('rest_framework.urls')),
]
By default DRF authenticates requests with the session of Django's login and with HTTP Basic authentication, which curl sends with the
option -u. Basic authentication sends the password with every request, so outside development it is only acceptable over
HTTPS; the users themselves are those of Django authentication. Without credentials the POST is
refused. The status is 403 rather than 401, because the first authentication class, the session one, defines no
WWW-Authenticate header. With alice's password the book is created and alice is its owner. But the last command shows the
remaining problem: alice could change the price of bob's book.
$ curl -s localhost:8000/api/books/1/; echo
{"id":1,"title":"Clean Code","author":"Robert C. Martin","published":2008,"price":"37.50","owner":"alice"}
$ curl -s -i localhost:8000/api/books/ -H 'Content-Type: application/json' -d '{"title": "Clean Architecture", "author": "Robert C. Martin", "published": 2017, "price": "36.99"}' | sed -n '1p;$p'
HTTP/1.1 403 Forbidden
{"detail":"Authentication credentials were not provided."}
$ curl -s -i localhost:8000/api/books/ -H 'Content-Type: application/json' -d '{"title": "Clean Architecture", "author": "Robert C. Martin", "published": 2017, "price": "36.99"}' -u alice:wrong | sed -n '1p;$p'
HTTP/1.1 403 Forbidden
{"detail":"Invalid username/password."}
$ curl -s localhost:8000/api/books/ -H 'Content-Type: application/json' -d '{"title": "Clean Architecture", "author": "Robert C. Martin", "published": 2017, "price": "36.99"}' -u alice:s3cret-alice; echo
{"id":8,"title":"Clean Architecture","author":"Robert C. Martin","published":2017,"price":"36.99","owner":"alice"}
$ curl -s -X PATCH localhost:8000/api/books/2/ -H 'Content-Type: application/json' -d '{"price": "1.00"}' -u alice:s3cret-alice; echo
{"id":2,"title":"Fluent Python","author":"Luciano Ramalho","published":2022,"price":"1.00","owner":"bob"}
Object-level permissions
A permission class has two hooks: has_permission() runs for every request, has_object_permission() for requests
on a single object, after the view has loaded it. Our permission allows the safe methods (GET, HEAD, OPTIONS) to everyone and the
others only to the owner. The message attribute replaces the default error message.
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
message = 'Only the owner can change this book.'
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user
The viewset lists both permissions; a request must pass all of them.
from rest_framework import permissions, viewsets
from .models import Book
from .permissions import IsOwnerOrReadOnly
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.select_related('owner')
serializer_class = BookSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
Alice can no longer change bob's book, while bob can, and he uses it to restore the price. The owner sent by bob is ignored,
because the field is read-only. Bob cannot delete the book alice created, and alice can.
$ curl -s -X PATCH localhost:8000/api/books/2/ -H 'Content-Type: application/json' -d '{"price": "1.00"}' -u alice:s3cret-alice; echo
{"detail":"Only the owner can change this book."}
$ curl -s -X PATCH localhost:8000/api/books/2/ -H 'Content-Type: application/json' -d '{"price": "59.99"}' -u bob:s3cret-bob; echo
{"id":2,"title":"Fluent Python","author":"Luciano Ramalho","published":2022,"price":"59.99","owner":"bob"}
$ curl -s -X PATCH localhost:8000/api/books/2/ -H 'Content-Type: application/json' -d '{"owner": "alice"}' -u bob:s3cret-bob | jq -c '{id, owner}'
{"id":2,"owner":"bob"}
$ curl -s -o /dev/null -w '%{http_code}\n' -X DELETE localhost:8000/api/books/8/ -u bob:s3cret-bob
403
$ curl -s -o /dev/null -w '%{http_code}\n' -X DELETE localhost:8000/api/books/8/ -u alice:s3cret-alice
204
In the browsable API, the link Log in in the top right corner uses the views of api-auth/. Logged in as alice, the
page of her book offers the buttons and forms for DELETE, PUT, and PATCH; on bob's books they are missing, because the browsable API asks
the permissions before it renders a form.
Testing the API
APITestCase is Django's TestCase with DRF's APIClient. The client encodes the data with
format='json', its responses carry the parsed data, and force_authenticate() logs a user in without
a password.
from django.contrib.auth.models import User
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')
cls.bob = User.objects.create_user('bob')
cls.book = Book.objects.create(title='Refactoring', author='Martin Fowler',
published=2018, price='47.99', owner=cls.alice)
def test_anyone_can_read(self):
response = self.client.get('/api/books/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data[0]['owner'], 'alice')
def test_anonymous_cannot_create(self):
response = self.client.post('/api/books/', {'title': 'X'}, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_create_sets_owner(self):
self.client.force_authenticate(self.bob)
data = {'title': 'Fluent Python', 'author': 'Luciano Ramalho',
'published': 2022, 'price': '59.99'}
response = self.client.post('/api/books/', data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Book.objects.get(pk=response.data['id']).owner, self.bob)
def test_only_owner_can_update(self):
self.client.force_authenticate(self.bob)
url = f'/api/books/{self.book.pk}/'
response = self.client.patch(url, {'price': '1.00'}, format='json')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.client.force_authenticate(self.alice)
response = self.client.patch(url, {'price': '45.00'}, format='json')
self.assertEqual(response.data['price'], '45.00')
The four tests check reading, the refused anonymous POST, the owner of a new book, and the object permission.
$ uv run python manage.py test 2>&1 Found 4 test(s). Creating test database for alias 'default'... System check identified no issues (0 silenced). .... ---------------------------------------------------------------------- Ran 4 tests in 0.009s OK Destroying test database for alias 'default'...
Source
Django REST framework documentation
Django REST framework: Serializers
Django REST framework: ViewSets
Django REST framework: Permissions
In this article we have built a JSON API with Django REST framework: we have serialized and validated books with a
Serializer and a ModelSerializer, written the API as function views, as APIView classes, as generic
views, and as a ModelViewSet with a router, explored it in the browsable API, restricted changes to the owner with permissions,
and tested it with APITestCase. Related articles are Django JsonResponse,
Django class-based views, Django authentication, and
Django permissions and groups. Token and JWT authentication, pagination, filtering, and
throttling are covered in Django REST framework authentication and pagination.
Author
List all Django tutorials.