Build a Django REST API Framework Project with DRF Step by Step

PIXELATING BITS, THE BITS THAT WILL GROW YOUR BRAND!

Build a Django REST API Framework Project with DRF Step by Step

PIXELATING BITS, THE BITS THAT WILL GROW YOUR BRAND!

Build a Django REST API Framework Project with DRF Step by Step

You have a Django project, a front end or mobile app that needs JSON, and no clear path from one to the other. This tutorial takes you from an empty virtualenv to a working, authenticated CRUD API (create, read, update, delete), with a command to run and an output to check at every step.

Django REST framework (DRF) is a powerful and flexible toolkit built on top of Django that turns your models into web API endpoints. It handles serialization, requests, responses, authentication and permissions for you. The minimal path is: install djangorestframework, add rest_framework to INSTALLED_APPS, write a model, a serializer and a ViewSet, then register the ViewSet with a router.

How DRF works in one minute

A request arrives at a URL, and the router sends it to a ViewSet. The ViewSet asks the serializer to convert a model instance into JSON (serialization). It also asks the serializer to validate incoming JSON and turn it into a model instance (deserialization).

Authentication identifies who is calling. Permissions decide what they may do. Pagination limits how much data comes back. JSON is the usual format, though DRF can render other formats such as XML through its renderers.

The example project is a small books API with a Book model. Every command below assumes a Unix-like shell. On Windows, activate the virtualenv with venv\Scripts\activate.

python code

Requirements and installation

DRF needs a supported release of Python and Django. The project officially supports only the latest patch release of each Python and Django series, so check the official documentation for the current version table before you start. Optional packages add Markdown support to the browsable API and object-level permissions through django-guardian. You install DRF with pip, as in Step 1.

python code

Step-by-step: from empty virtualenv to working API

Step 1: Create the environment and install DRF

python -m venv venv
source venv/bin/activate
pip install django djangorestframework
django-admin startproject config .
python manage.py startapp books

Check: pip list shows both Django and djangorestframework, and manage.py sits next to the config folder.

Step 2: Add the apps to settings.py

INSTALLED_APPS = [
    # default Django apps...
    'rest_framework',
    'rest_framework.authtoken',
    'books',
]

Check: python manage.py check prints System check identified no issues.

Step 3: Create the model

In books/models.py, define the model fields. Each field maps to a database column through the Django ORM (object-relational mapper, the layer that lets you work with database rows as Python objects).

from django.conf import settings
from django.db import models

class Book(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=120)
    published = models.DateField(null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created']

    def __str__(self):
        return self.title
python manage.py makemigrations
python manage.py migrate

Check: the output lists Create model Book. It then shows Applying books.0001_initial... OK.

Step 4: Write the serializer

A serializer converts model instances to JSON and validates incoming data. ModelSerializer generates the fields and basic validation from the model automatically.

# books/serializers.py
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', 'owner']

Check: open python manage.py shell and run from books.serializers import BookSerializer; print(BookSerializer()). It prints the list of fields.

Step 5: Build the ViewSet and permissions

A ModelViewSet provides list, create, retrieve, update, partial update and destroy in one class. A custom permission class lets only the owner modify a book.

# books/permissions.py
from rest_framework import permissions

class IsOwnerOrReadOnly(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        if request.method in permissions.SAFE_METHODS:
            return True
        return obj.owner == request.user
# books/views.py
from rest_framework import viewsets, permissions
from .models import Book
from .serializers import BookSerializer
from .permissions import IsOwnerOrReadOnly

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
    permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly]

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

Check: the file imports without errors once the router is added in the next step.

Step 6: Register a router and the URL patterns

A router generates the URL patterns for a ViewSet, so you do not write each one by hand. Create the app routes first.

# books/urls.py
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
router.register('books', BookViewSet, basename='book')
urlpatterns = router.urls

Then include them from the project urls.py file.

# config/urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework.authtoken.views import obtain_auth_token

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('books.urls')),
    path('api/token/', obtain_auth_token),
    path('api-auth/', include('rest_framework.urls')),
]

The DefaultRouter generates /api/books/ and /api/books/{id}/, plus an API root page. DRF also ships a SimpleRouter, which does the same without the root page.

Step 7: Configure authentication and pagination

Global settings for a DRF API live in one dictionary named REST_FRAMEWORK in settings.py.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10,
}

Token authentication is the simplest option and ships with DRF. If you need expiring access tokens and refresh tokens, the third-party djangorestframework-simplejwt package is the usual JWT (JSON Web Token) choice. The PAGE_SIZE of 10 is just a common starting point.

python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Check: the server starts and the terminal shows Starting development server at http://127.0.0.1:8000/.

Step 8: Test the endpoints with curl

curl is a command-line tool that sends HTTP requests. First, request a token with the superuser credentials.

curl -X POST http://127.0.0.1:8000/api/token/ \
  -d "username=admin&password=yourpassword"
# {"token":"9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"}

Your token will differ. Then create, list, update and delete a book. Start with the token and a create call.

TOKEN=your_token_here

# Create
curl -X POST http://127.0.0.1:8000/api/books/ \
  -H "Authorization: Token $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"Dune","author":"Frank Herbert"}'
# {"id":1,"title":"Dune","author":"Frank Herbert","published":null,"owner":"admin"}
# List (public, read-only)
curl http://127.0.0.1:8000/api/books/
# {"count":1,"next":null,"previous":null,"results":[...]}

# Partial update
curl -X PATCH http://127.0.0.1:8000/api/books/1/ \
  -H "Authorization: Token $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"published":"1965-08-01"}'

# Delete (expect HTTP 204)
curl -i -X DELETE http://127.0.0.1:8000/api/books/1/ \
  -H "Authorization: Token $TOKEN"

Try the create call without the header. You should get status code 401 with Authentication credentials were not provided. That confirms the permissions work.

Step 9: Explore the browsable API

Open http://127.0.0.1:8000/api/ in a browser. DRF renders an HTML interface for every endpoint, with forms to send POST and PUT requests, which is handy when you do not want to leave the browser. Log in through the /api-auth/login/ link to test as a user.

Step 10: Add automated tests

# books/tests.py
from django.contrib.auth.models import User
from rest_framework.test import APITestCase

class BookAPITests(APITestCase):
    def setUp(self):
        self.user = User.objects.create_user('ann', password='pass12345')

    def test_anonymous_cannot_create(self):
        r = self.client.post('/api/books/', {'title': 'A', 'author': 'B'})
        self.assertEqual(r.status_code, 401)

    def test_user_can_create(self):
        self.client.force_authenticate(self.user)
        r = self.client.post('/api/books/', {'title': 'A', 'author': 'B'})
        self.assertEqual(r.status_code, 201)

Run python manage.py test.

Check: the output ends with Ran 2 tests and OK.

python code

Authentication versus authorization

Authentication answers “who are you?” and is handled by the token or session classes. Authorization answers “what may you do?” and is handled by permission classes such as IsAuthenticatedOrReadOnly and the custom IsOwnerOrReadOnly above. Mixing them up is the root of many confusing 401 and 403 responses.

DRF also offers throttling, which limits how many requests a client can make in a period. Unlike permissions, it is a temporary state. Serve any token-based API over HTTPS in production, because tokens act like passwords.

python code

Pitfalls that cost beginners the most time

SymptomCauseFix
ModuleNotFoundError: rest_frameworkPackage not installed in the active virtualenvActivate the venv, run pip install djangorestframework
Token request returns a table errorrest_framework.authtoken added but not migratedRun python manage.py migrate
403 on POST in the browserNot logged in, or CSRF with session authenticationLog in via the browsable API or send a token header
owner is required on createOwner not set by the viewUse perform_create and a read-only owner field
Unordered pagination warningModel has no default orderingAdd ordering in Meta or order the queryset

FAQ

When should I choose DRF over plain Django views?

Choose DRF when you need several endpoints with validation, authentication, permissions and pagination, because rewriting those by hand is slow and error-prone. Plain Django views with JsonResponse are enough for one or two tiny endpoints with no auth. Once you copy validation code twice, DRF usually pays off.

Function-based views, class-based views or ViewSets?

Function-based views with @api_view suit one-off endpoints with custom logic. Class-based APIView and generic views fit a single resource with a few actions. ViewSets with routers fit standard CRUD on a model, and you can still add custom actions with the @action decorator.

Is Django still worth learning for APIs in 2026?

Yes, Django remains widely used for web backends, and DRF is still a common way to expose a Django project as a REST API. The skills transfer well, since serializers, routing and permissions are concepts you meet in any API framework. REST itself is not hard to learn once you understand HTTP methods and status codes.

Which path fits you

If you are building a standard resource API, stay with ModelViewSet, a router and token authentication. Move to JWT only when you need expiring tokens. If your endpoints are mostly custom logic, reach for APIView or function-based views.

Clone this example, run the tests, and adapt the Book model to your own data to turn it into the base of your project.

Contact Details

Copyright © 2022 Pixelating Bits. All Rights Reserved.