Web frameworks · Intermediate · 26 min
Build a REST API with Django REST Framework
By Padding · Updated 18 Nov 2026
python:3.15-slim · Python 3.15 · Django 6.1 · djangorestframework 3.18
You will build a JSON API for recipes with Django 6.1 and Django REST Framework 3.18, with validation, token sign-in, owner-only edits, pagination, filtering, the browsable API and a passing test suite.
On this page
Django REST Framework (DRF) is the package most Django teams use to put a JSON API in front of their models. It adds serializers, which turn model instances into JSON and check incoming data; viewsets, which bundle the list, create, read, update and delete actions for one model; and routers, which give those actions their URLs. Authentication, permissions, pagination and filtering are switches in the same system.
You will build a small recipes API. Anyone can read recipes, signed-in users can add them, and only the person who added a recipe can change or delete it. You call it with curl as two users, Amara and Bola, look at it in the browser, and finish with tests written with DRF's APIClient. If you have not used Django before, start with create your first Django 6 app: this tutorial assumes you know what manage.py, apps, models and migrations are.
Step 1 · Create the project and add DRF
Start a fresh project in a demo folder, add Django, DRF and django-filter, and create a Django project and a recipes app. The version ranges keep each package in the series this tutorial was written for:
mkdir -p ~/recipes-api-demo
cd ~/recipes-api-demo
uv init --no-package
rm main.py
uv add "django>=6.1,<6.2" "djangorestframework>=3.18,<3.19" "django-filter>=26.2,<27"
uv run django-admin startproject config .
uv run python manage.py startapp recipesDRF is a normal Django app, so it goes in INSTALLED_APPS. Add it, its token app, django-filter and your own app to the end of config/settings.py, together with a first REST_FRAMEWORK block. Appending keeps the generated file untouched above it:
cat >> config/settings.py <<'PY'
INSTALLED_APPS += [
"rest_framework",
"rest_framework.authtoken",
"django_filters",
"recipes",
]
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.TokenAuthentication",
"rest_framework.authentication.SessionAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticatedOrReadOnly",
],
}
PY
uv run python manage.py check
uv run python -c "import django, rest_framework; print(django.get_version(), rest_framework.VERSION)"The two settings say how a request proves who it is and what anyone may do by default. TokenAuthentication reads an Authorization: Token <key> header, which suits scripts and mobile apps. SessionAuthentication reuses the Django login cookie, which the browsable API uses later. IsAuthenticatedOrReadOnly lets anyone read and only signed-in users write.
Check it worked
check prints System check identified no issues (0 silenced). The last command prints the two versions, something like 6.1.3 3.18.3. If check complains about a missing module, look at the spelling in INSTALLED_APPS: the package is installed as django-filter but imported as django_filters.
Step 2 · Model a recipe
Each recipe belongs to a user, has a title, a cuisine from a fixed list, a cooking time in minutes, ingredients and an optional method. Replace recipes/models.py:
cat > recipes/models.py <<'PY'
from django.conf import settings
from django.db import models
class Recipe(models.Model):
class Cuisine(models.TextChoices):
WEST_AFRICAN = "west-african", "West African"
EAST_AFRICAN = "east-african", "East African"
NORTH_AFRICAN = "north-african", "North African"
SOUTHERN_AFRICAN = "southern-african", "Southern African"
OTHER = "other", "Other"
owner = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="recipes"
)
title = models.CharField(max_length=120)
cuisine = models.CharField(
max_length=20, choices=Cuisine.choices, default=Cuisine.OTHER
)
minutes = models.PositiveIntegerField()
ingredients = models.TextField()
method = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ["-created", "-id"]
def __str__(self):
return self.title
PY
uv run python manage.py makemigrations recipes
uv run python manage.py migrateThe default ordering matters for an API more than for a page: pagination needs a stable order, or the same recipe can turn up on two pages. Newest first, with id as a tie-breaker, is stable.
Check it worked
makemigrations prints recipes/migrations/0001_initial.py and + Create model Recipe. migrate ends with lines such as Applying authtoken.0004_alter_tokenproxy_options... OK and Applying recipes.0001_initial... OK. The authtoken lines show DRF's token table was created too.
Step 3 · Write a serializer that validates input
A serializer sits between JSON and the model. ModelSerializer reads the field types and limits from the model, so max_length=120 and the cuisine choices are enforced with no extra code. You add the rules the model cannot express. Create recipes/serializers.py:
cat > recipes/serializers.py <<'PY'
from rest_framework import serializers
from .models import Recipe
class RecipeSerializer(serializers.ModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="recipe-detail")
owner = serializers.ReadOnlyField(source="owner.username")
class Meta:
model = Recipe
fields = [
"id", "url", "owner", "title", "cuisine",
"minutes", "ingredients", "method", "created",
]
def validate_title(self, value):
value = value.strip()
if len(value) < 3:
raise serializers.ValidationError("Use at least 3 characters.")
return value
def validate_minutes(self, value):
if not 1 <= value <= 24 * 60:
raise serializers.ValidationError("Give a time between 1 and 1440 minutes.")
return value
def validate(self, attrs):
request = self.context.get("request")
title = attrs.get("title")
if request is None or title is None:
return attrs
clash = Recipe.objects.filter(owner=request.user, title__iexact=title)
if self.instance is not None:
clash = clash.exclude(pk=self.instance.pk)
if clash.exists():
raise serializers.ValidationError(
{"title": "You already have a recipe with this title."}
)
return attrs
PYThree kinds of rule are at work:
- A method called
validate_<field>checks one field and returns the cleaned value.validate_titlealso trims spaces, so" Jollof rice "is stored asJollof rice. validatesees all the fields at once. Here it stops one user from having two recipes with the same title. It needs the request to know who the user is, which the view passes in later; without one it skips the check.owneris aReadOnlyField. Clients see the owner's username, but anything they send forowneris ignored. The view sets it from the signed-in user instead.
url gives every recipe a link to itself. The name recipe-detail comes from the router you add next.
Try the serializer from the Django shell, with no web server involved. -v 0 hides the shell's note about imported models:
uv run python manage.py shell -v 0 -c '
import json
from recipes.serializers import RecipeSerializer
bad = RecipeSerializer(data={"title": " Jo ", "cuisine": "nordic", "minutes": 0, "ingredients": ""})
print(bad.is_valid())
print(json.dumps(bad.errors, indent=2))
good = RecipeSerializer(data={"title": " Jollof rice ", "cuisine": "west-african", "minutes": 75, "ingredients": "rice, tomatoes, peppers"})
print(good.is_valid(), repr(good.validated_data["title"]))
'Check it worked
The first line is False, followed by one error list per bad field: "Use at least 3 characters." for the title, "\"nordic\" is not a valid choice." for the cuisine, "Give a time between 1 and 1440 minutes." for minutes and "This field may not be blank." for ingredients. The last line is True 'Jollof rice', with the spaces gone. This shape, a field name mapped to a list of messages, is exactly what API clients receive in a 400 response.
Step 4 · Expose the API with a ViewSet and a router
A ModelViewSet provides list, create, retrieve, update, partial update and delete for one model. You give it the records and the serializer, and override perform_create so a new recipe is saved with the signed-in user as owner. Replace recipes/views.py and create recipes/urls.py:
cat > recipes/views.py <<'PY'
from rest_framework import viewsets
from .models import Recipe
from .serializers import RecipeSerializer
class RecipeViewSet(viewsets.ModelViewSet):
queryset = Recipe.objects.select_related("owner")
serializer_class = RecipeSerializer
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
PY
cat > recipes/urls.py <<'PY'
from rest_framework.routers import DefaultRouter
from .views import RecipeViewSet
router = DefaultRouter()
router.register("recipes", RecipeViewSet)
urlpatterns = router.urls
PY
cat > config/urls.py <<'PY'
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("api/", include("recipes.urls")),
path("api-auth/", include("rest_framework.urls")),
]
PYThe router writes two URL patterns, recipes/ (named recipe-list) and recipes/<pk>/ (named recipe-detail), and DefaultRouter adds an API root at /api/ that links to them. select_related("owner") loads each owner in the same query, so a list of recipes does not run one extra query per row. api-auth/ adds DRF's login and logout pages for the browsable API.
Start the development server in a second terminal, from ~/recipes-api-demo. It reloads itself when you save a file, so leave it running:
uv run python manage.py runserverAsk for the API root and the empty list, then try to add a recipe without signing in:
curl -s http://127.0.0.1:8000/api/
echo
curl -s http://127.0.0.1:8000/api/recipes/
echo
curl -s -i --json '{"title": "Jollof rice", "minutes": 75, "ingredients": "rice"}' http://127.0.0.1:8000/api/recipes/ | grep -E '^HTTP|^WWW-Authenticate|detail'Now make two users, Amara and Bola, each with an API token. The command writes each token into a header file that only you can read, so the key stays out of your shell history and you can pass it to curl with -H @file. These users have no password: they can only use the API with their token.
for name in amara bola; do
(umask 077; uv run python manage.py shell -v 0 -c "
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
user = User.objects.filter(username='$name').first() or User.objects.create_user('$name')
token, _ = Token.objects.get_or_create(user=user)
print(f'Authorization: Token {token.key}')
" > "$name.header")
done
echo '*.header' >> .gitignore
ls -l amara.header bola.headerAdd a recipe as Amara. The title has an accent on purpose:
curl -s -H @amara.header --json '{"title": "Ndolé", "cuisine": "west-african", "minutes": 120, "ingredients": "bitter leaves, groundnuts, beef"}' http://127.0.0.1:8000/api/recipes/ | python3 -m json.tool --no-ensure-asciiCheck it worked
The root prints {"recipes":"http://127.0.0.1:8000/api/recipes/"} and the list prints []. The anonymous POST shows HTTP/1.1 401 Unauthorized, WWW-Authenticate: Token and {"detail":"Authentication credentials were not provided."}. The response is 401 rather than 403 because TokenAuthentication is listed first and tells the client how to sign in. Both header files show -rw-------. Amara's POST returns the new recipe with "id": 1, "owner": "amara", a url ending in /api/recipes/1/ and the title Ndolé with its accent intact: DRF sends UTF-8 JSON by default, so names in Yorùbá, Amharic or French come through as written.
Step 5 · Let only owners change a recipe
The API has a hole. Bola is signed in, so IsAuthenticatedOrReadOnly lets him change Amara's recipe. Try it:
curl -s -o /dev/null -w '%{http_code}\n' -H @bola.header -X PATCH --json '{"minutes": 5}' http://127.0.0.1:8000/api/recipes/1/That prints 200, and Amara's two-hour ndolé now says five minutes. Close the hole with an object-level permission. Create recipes/permissions.py:
cat > recipes/permissions.py <<'PY'
from rest_framework import permissions
class IsOwnerOrReadOnly(permissions.BasePermission):
message = "Only the owner of this recipe can change it."
def has_object_permission(self, request, view, obj):
if request.method in permissions.SAFE_METHODS:
return True
return obj.owner == request.user
PYhas_object_permission runs once DRF has loaded the recipe, for retrieve, update and delete. SAFE_METHODS are GET, HEAD and OPTIONS, which change nothing. Use it in the viewset next to the default rule. Setting permission_classes on a view replaces the default from settings, so list both:
cat > recipes/views.py <<'PY'
from rest_framework import permissions, viewsets
from .models import Recipe
from .permissions import IsOwnerOrReadOnly
from .serializers import RecipeSerializer
class RecipeViewSet(viewsets.ModelViewSet):
queryset = Recipe.objects.select_related("owner")
serializer_class = RecipeSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
PYRun Bola's change again, then a delete, then let Amara put the right time back:
curl -s -H @bola.header -X PATCH --json '{"minutes": 5}' http://127.0.0.1:8000/api/recipes/1/
echo
curl -s -o /dev/null -w '%{http_code}\n' -H @bola.header -X DELETE http://127.0.0.1:8000/api/recipes/1/
curl -s -H @amara.header -X PATCH --json '{"minutes": 120}' http://127.0.0.1:8000/api/recipes/1/ | python3 -m json.tool --no-ensure-asciiCheck it worked
Bola's PATCH now answers {"detail":"Only the owner of this recipe can change it."} and his DELETE prints 403. Amara's PATCH returns the recipe with "minutes": 120. Open http://127.0.0.1:8000/api/recipes/1/ in a browser or with curl and the recipe is still there. A PATCH changes only the fields you send; a PUT replaces the whole recipe and needs every required field.
Step 6 · Add pagination, filtering, search and ordering
An unpaginated list returns every row in one response. That gets slow for the server and expensive for the client, especially on a phone on prepaid mobile data. Turn on page-number pagination and the three filter backends for the whole project:
cat >> config/settings.py <<'PY'
REST_FRAMEWORK |= {
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 5,
"DEFAULT_FILTER_BACKENDS": [
"django_filters.rest_framework.DjangoFilterBackend",
"rest_framework.filters.SearchFilter",
"rest_framework.filters.OrderingFilter",
],
}
PYEach backend reads its own setting from the view: filterset_fields for exact matches with django-filter, search_fields for the ?search= text search and ordering_fields for ?ordering=. Only the fields you list can be used, which keeps clients from sorting on columns you never meant to expose. Write the final viewset:
cat > recipes/views.py <<'PY'
from rest_framework import permissions, viewsets
from .models import Recipe
from .permissions import IsOwnerOrReadOnly
from .serializers import RecipeSerializer
class RecipeViewSet(viewsets.ModelViewSet):
queryset = Recipe.objects.select_related("owner")
serializer_class = RecipeSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]
filterset_fields = ["cuisine", "owner__username"]
search_fields = ["title", "ingredients"]
ordering_fields = ["minutes", "created", "title"]
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
PYAdd six more recipes as Amara, so there is more than one page:
while IFS='|' read -r title cuisine minutes ingredients; do
curl -s -o /dev/null -w "%{http_code} $title\n" -H @amara.header \
--json "{\"title\": \"$title\", \"cuisine\": \"$cuisine\", \"minutes\": $minutes, \"ingredients\": \"$ingredients\"}" \
http://127.0.0.1:8000/api/recipes/
done <<'DATA'
Jollof rice|west-african|75|rice, tomatoes, peppers, onions
Pilau|east-african|60|rice, beef, pilau masala
Chakalaka|southern-african|30|beans, carrots, peppers
Shakshuka|north-african|25|eggs, tomatoes, peppers
Egusi soup|west-african|90|melon seeds, spinach, palm oil
Ugali|east-african|20|maize flour, water
DATANow page through, filter and search:
curl -s http://127.0.0.1:8000/api/recipes/ | python3 -c 'import json, sys; d = json.load(sys.stdin); print(d["count"], d["next"], len(d["results"]))'
curl -s "http://127.0.0.1:8000/api/recipes/?page=2" | python3 -c 'import json, sys; print([r["title"] for r in json.load(sys.stdin)["results"]])'
curl -s "http://127.0.0.1:8000/api/recipes/?cuisine=west-african" | python3 -c 'import json, sys; print([r["title"] for r in json.load(sys.stdin)["results"]])'
curl -s "http://127.0.0.1:8000/api/recipes/?search=peppers&ordering=minutes" | python3 -c 'import json, sys; print([r["title"] for r in json.load(sys.stdin)["results"]])'
curl -s "http://127.0.0.1:8000/api/recipes/?cuisine=nordic"
echoCheck it worked
The six POSTs each print 201 and a title. The list is now an envelope: the first line prints 7 http://127.0.0.1:8000/api/recipes/?page=2 5, meaning seven recipes in all, a link to the next page and five on this one. Page two holds the two oldest, ['Jollof rice', 'Ndolé']. The cuisine filter prints ['Egusi soup', 'Jollof rice', 'Ndolé'], and the search for peppers, shortest first, prints ['Shakshuka', 'Chakalaka', 'Jollof rice']. An unknown cuisine is a 400 with a message rather than an empty list: {"cuisine":["Select a valid choice. nordic is not one of the available choices."]}.
Step 7 · Explore the browsable API
DRF answers browsers with HTML and scripts with JSON from the same URL, depending on the Accept header. Open http://127.0.0.1:8000/api/ in a browser. You see the API root, can click through to the recipe list and see the pagination links, a Filters button and the raw JSON for each response.
To use the forms for adding and editing, you need to be signed in with a password. Create a superuser in the first terminal; it asks for a username, an email address and a password:
uv run python manage.py createsuperuserThen use the Log in link at the top right of the browsable API, which goes to the api-auth/ pages you added. Signed in, the recipe list shows a form at the bottom to POST a new recipe, and a recipe you own shows PUT, PATCH and DELETE controls. Open one of Amara's recipes and the edit controls are missing or refused, because the owner rule applies to you too. Validation errors appear next to the form fields, with the same messages you saw in the shell.
Check the HTML version from the terminal:
curl -s -H 'Accept: text/html' http://127.0.0.1:8000/api/recipes/ | grep -o '<title>[^<]*</title>'Check it worked
curl prints <title>Recipe List – Django REST framework</title>. In the browser the page heading reads Recipe List and the response panel shows HTTP 200 OK above the paginated JSON. The browsable API is helpful during development and harmless in production for public read-only data, but you can switch it off by setting DEFAULT_RENDERER_CLASSES to only rest_framework.renderers.JSONRenderer.
Step 8 · Test the API with APIClient
The curl checks prove the API works today. Tests keep it working when you change it. DRF's APITestCase runs each test in a transaction on a temporary database, and APIClient.force_authenticate signs a user in without tokens or passwords. Replace recipes/tests.py:
cat > recipes/tests.py <<'PY'
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient, APITestCase
from .models import Recipe
LIST_URL = "/api/recipes/"
class RecipeApiTests(APITestCase):
def setUp(self):
self.amara = User.objects.create_user("amara")
self.bola = User.objects.create_user("bola")
self.recipe = Recipe.objects.create(
owner=self.amara, title="Ndolé", cuisine="west-african",
minutes=120, ingredients="bitter leaves, groundnuts",
)
self.detail_url = f"{LIST_URL}{self.recipe.pk}/"
def as_user(self, user):
client = APIClient()
client.force_authenticate(user=user)
return client
def test_anyone_can_list(self):
response = self.client.get(LIST_URL)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data["count"], 1)
self.assertEqual(response.data["results"][0]["owner"], "amara")
def test_anonymous_cannot_create(self):
response = self.client.post(LIST_URL, {"title": "Pilau"}, format="json")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_create_sets_owner_from_request(self):
data = {"title": "Pilau", "cuisine": "east-african", "minutes": 60,
"ingredients": "rice, beef", "owner": "bola"}
response = self.as_user(self.amara).post(LIST_URL, data, format="json")
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Recipe.objects.get(title="Pilau").owner, self.amara)
def test_validation_errors_are_returned(self):
data = {"title": " x ", "cuisine": "west-african", "minutes": 0, "ingredients": "rice"}
response = self.as_user(self.amara).post(LIST_URL, data, format="json")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(set(response.data), {"title", "minutes"})
def test_owner_can_update(self):
response = self.as_user(self.amara).patch(self.detail_url, {"minutes": 100}, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.recipe.refresh_from_db()
self.assertEqual(self.recipe.minutes, 100)
def test_other_user_cannot_update_or_delete(self):
client = self.as_user(self.bola)
response = client.patch(self.detail_url, {"minutes": 5}, format="json")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
response = client.delete(self.detail_url)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertTrue(Recipe.objects.filter(pk=self.recipe.pk).exists())
def test_filter_by_cuisine(self):
Recipe.objects.create(owner=self.bola, title="Ugali", cuisine="east-african",
minutes=20, ingredients="maize flour, water")
response = self.client.get(LIST_URL, {"cuisine": "east-african"})
self.assertEqual([r["title"] for r in response.data["results"]], ["Ugali"])
PY
uv run python manage.py testEach test names one promise the API makes. test_create_sets_owner_from_request sends "owner": "bola" while signed in as Amara, to prove a client cannot claim someone else's name. response.data is the Python data before it became JSON, which is easier to compare than the raw bytes.
Check it worked
The runner prints Found 7 test(s)., Ran 7 tests and OK, with a line of seven dots. Break the permission on purpose to see a test catch it: remove IsOwnerOrReadOnly from permission_classes, run the tests again, and test_other_user_cannot_update_or_delete fails with AssertionError: 200 != 403. Put it back before you go on.
When you are done, stop the server with Ctrl+C in its terminal.
The header files hold live tokens for this project, so they go with it. Remove the demo project:
cd ~
rm -rf ~/recipes-api-demoNext steps
- Give people a way to sign up and sign in with a password: add sign-up, login and password reset to a Django app.
- Compare the same kind of API in a different style, with type hints doing the validation: build a REST API with FastAPI.
- Run the project behind a real web server: deploy a Django app with Gunicorn and Nginx.
- DRF's built-in tokens are one plain key per user that never expires. Before you ship, read the authentication guide at django-rest-framework.org and decide whether you need expiring tokens or a third-party package.
Related tutorials
- How to Create Your First Django 6 AppYou will create a Django 6.1 project with uv on Python 3.15, build a small bookmarks app with a database model, an admin screen, a page and a test, and see how the pieces connect.
- Add sign-up, login and password reset to a Django appYou will have a Django 6.1 notes app with a custom user model, sign-up, login, logout and a working password reset, where each user sees only their own notes and a test suite proves it.
- How to Build a REST API with FastAPIYou will build a small items API with FastAPI 0.163 on Python 3.15 that validates its input, returns the right HTTP status codes, never shows a stack trace to callers, documents itself, and has automated tests.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials