← Back to Django, page 4

django-0077 · Medium mid

How does API versioning work in Django REST Framework, and how do URLPathVersioning and AcceptHeaderVersioning differ?

DRF versioning schemes decide how the client names a version and expose it as request.version. URLPathVersioning puts it in the path (/api/v1/...), AcceptHeaderVersioning in the Accept media type parameter, NamespaceVersioning uses URL namespaces, and QueryParameterVersioning uses ?version=. The view reads request.version to choose serializers or behaviour, and DEFAULT_VERSION, ALLOWED_VERSIONS and VERSION_PARAM validate input.

Full answer

Versioning lets you change responses without breaking existing clients. Configure it in REST_FRAMEWORK:

python
REST_FRAMEWORK = {
    "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
    "DEFAULT_VERSION": "v1",
    "ALLOWED_VERSIONS": ["v1", "v2"],
}

Schemes:

  • URLPathVersioning: path("api/<version>/students/", ...). Visible, cache-friendly, easy to test with curl, and the most common choice.
  • AcceptHeaderVersioning: Accept: application/json; version=2. Keeps URLs stable, but is harder to cache and test.
  • NamespaceVersioning: separate include(..., namespace="v1") URLconfs.
  • QueryParameterVersioning: ?version=2; simple, but easy to omit.
  • HostNameVersioning: v2.api.example.com.

Inside a view: request.version holds the value, and reverse("student-list", request=request) builds URLs that include the version. Override get_serializer_class() to choose a different serializer:

python
def get_serializer_class(self):
    return StudentV2Serializer if self.request.version == "v2" else StudentV1Serializer

Unknown versions give 404 (URLPath) or 406 (Accept header) when ALLOWED_VERSIONS is set.

Practice:

  • Version only for breaking changes (removing or renaming fields, changing types). Adding optional fields is not breaking.
  • Keep the number of live versions small, announce deprecation (the Deprecation and Sunset headers), and share code through serializers that subclass each other.
  • Avoid copy-pasting whole viewsets for each version.
  • Test every supported version.
python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    REST_FRAMEWORK={
        "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
        "DEFAULT_VERSION": "v1",
        "ALLOWED_VERSIONS": ["v1", "v2"],
    },
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "rest_framework", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from rest_framework import serializers
from rest_framework.response import Response
from rest_framework.test import APIClient
from rest_framework.views import APIView
from django.urls import path

class StudentV1(serializers.Serializer):
    name = serializers.CharField()


class StudentV2(StudentV1):
    roll_no = serializers.CharField()                      # additional field in the new version


class StudentDetail(APIView):
    def get(self, request, version):
        serializer_class = StudentV2 if request.version == "v2" else StudentV1
        return Response({"version": request.version, **serializer_class({"name": "Asha", "roll_no": "BCA-17"}).data})


urlpatterns = [path("api/<version>/students/1/", StudentDetail.as_view())]

c = APIClient()
print(c.get("/api/v1/students/1/").json())
print(c.get("/api/v2/students/1/").json())
print(c.get("/api/v3/students/1/").status_code)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. Requires `pip install djangorestframework`. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): {'version': 'v1', 'name': 'Asha'} {'version': 'v2', 'name': 'Asha', 'roll_no': 'BCA-17'} 404

Key points

  • Schemes: URL path, Accept header, namespace, query param, hostname
  • request.version drives serializer and behaviour choices
  • ALLOWED_VERSIONS rejects unknown versions
  • Only breaking changes need a new version
  • Keep live versions few and announce sunsets

Common mistakes

  • Creating a new version for every small change
  • Copy-pasting entire viewsets per version
  • Not setting ALLOWED_VERSIONS so any string is accepted
  • Forgetting to pass request to reverse() so URLs lose the version

Follow-ups

  • How would you deprecate and retire a version?
  • How do you version breaking changes in serializers without duplication?
  • Why is header-based versioning harder to cache?

Tips

  • List two schemes with trade-offs
  • Mention request.version
  • Say what counts as a breaking change