Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 39 ยท Versioning and Documentation

API Versioning in Django REST Framework

Version a Django REST Framework API without breaking clients: URLPathVersioning, AcceptHeaderVersioning, query and hostname schemes, request.version, per-version serializers and deprecation.

Once other people's code depends on your API, you can no longer change it freely. Renaming a field, changing a price from a number to an object, or removing an endpoint breaks every mobile app and script that expected the old shape, and mobile users update slowly. Versioning lets old clients keep the old behaviour while new clients get the new one, so you can improve the API without a flag day.

DRF supports versioning through a small pluggable system. A versioning class reads the version from the request (URL, header, query string, host name), and stores it in request.version. What you do with that value, for example choosing a different serializer, is up to you.

What counts as a breaking change?

Not every change needs a new version. Adding a new endpoint or a new optional field is safe, because well-written clients ignore fields they do not know. These need a version bump:

  • removing or renaming a field or endpoint;
  • changing a field's type or meaning (price: 12.5 becomes price: {"amount": ..., "currency": ...});
  • changing required inputs or validation rules so that previously valid requests fail;
  • changing status codes or error formats that clients parse.

Where can the version live?

URL path /v2/books/ โ€” visible and easy
Accept header version=2 in the media type
Query string /books/?version=2
Host name v2.api.example.com

DRF gives you one class per place

1 / 2

Settings

Python
# settings.py (read-only)
REST_FRAMEWORK = {
    "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning",
    "DEFAULT_VERSION": "v1",
    "ALLOWED_VERSIONS": ["v1", "v2"],
    "VERSION_PARAM": "version",
}

ALLOWED_VERSIONS makes DRF answer 404 for any other value. DEFAULT_VERSION is used when the client sends nothing (not for URL path versioning, where the URL always contains one). You can also set versioning_class on a single view.

URLPathVersioning

The version is a URL segment. This is the most popular scheme because it is explicit: you can see the version in logs, bookmark it, and route different versions to different servers. The URL pattern must capture a keyword argument named like VERSION_PARAM.

Python URLPathVersioning with a different serializer per version

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
/v1/books/ 200 {'id': 1, 'title': 'Night Trains', 'price': 12.5}
/v2/books/ 200 {'id': 1, 'title': 'Night Trains', 'price': {'amount': '12.50', 'currency': 'USD'}}
/v3/books/ 404 {'detail': 'Invalid version in URL path.'}

The view never looks at the URL itself: request.version carries the result, and a bad value is rejected before your code runs.

Header, query and host name schemes

The other classes work the same way and differ only in where they read the version. They are easy to compare side by side, because the view code does not change.

Class Client sends Notes
AcceptHeaderVersioning Accept: application/json; version=2 clean URLs; harder to test in a browser
QueryParameterVersioning /books/?version=2 easy to try; cache keys must include the query
HostNameVersioning Host: 2.example.com needs wildcard DNS and certificates
NamespaceVersioning URL namespace such as v2:book-list like URL path, but versions are separate URLconfs
Python Header, query and host name versioning side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
header, version=2                  200 2
header, nothing sent (default)     200 1
header, version=9                  406 {'detail': 'Invalid version in "Accept" header.'}
query ?version=2                   200 2
query, nothing sent (default)      200 1
host 2.example.com                 200 2
host example.com (default)         200 1

Building URLs with the right version

Inside a versioned view, call DRF's reverse() (not Django's) and pass request. The versioning class then adds the current version automatically, so a response from /v2/... links to /v2/.... With HyperlinkedModelSerializer, the request in the serializer context does the same, which is why generic views and viewsets pass it for you.

Python reverse() keeps the version of the current request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Output:

TEXT
{'books': 'http://api.test/v1/books/', 'version_in_use': 'v1', 'plain_django_reverse': '/v1/books/'}
{'books': 'http://api.test/v2/books/', 'version_in_use': 'v2', 'plain_django_reverse': '/v1/books/'}

Namespace versioning and organising code

NamespaceVersioning takes the version from the URL namespace. You keep one URL module per version (api/v1/urls.py, api/v2/urls.py) and include them under namespaces "v1" and "v2". The matching class is NamespaceVersioning, and request.version becomes the namespace. This is handy when v2 is mostly a different set of views.

A tidy project layout looks like this:

TEXT
api/
  v1/ serializers.py  views.py  urls.py
  v2/ serializers.py  views.py  urls.py
  common/ models.py  services.py      # shared business logic

Keep the models and business rules shared. Only the thin layer (serializers, view quirks) differs per version. If every version has its own copy of the logic, you will fix each bug several times.

A sensible deprecation process

  1. Announce the new version and the shutdown date of the old one in your docs and changelog.
  2. Add Deprecation and Sunset response headers (and a link to the migration guide) to the old version. A small mixin or middleware can do this.
  3. Log which clients still use the old version, using request.version and the API key or user agent.
  4. Contact heavy users directly before the date.
  5. Remove the old code once traffic is gone. Return 410 Gone for a while, rather than a mysterious 404.

Prefer additive evolution over new versions: adding fields and endpoints costs nothing, while every extra major version doubles testing. Most successful APIs have two live versions at a time, not ten.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does DRF store the version it read from the request?

    The versioning class sets request.version (and request.versioning_scheme) before your view runs.
  2. 2. Which change normally requires a new API version?

    Changing a field's type breaks clients that parse it. Additive changes are safe.
  3. 3. What does ALLOWED_VERSIONS do?

    A version not in the list is rejected before the view runs (404 NotFound).
  4. 4. Why call rest_framework.reverse.reverse(..., request=request) in a versioned view?

    With the request, the versioning scheme can add the current version to the generated URL.

Summary

  • Version only for breaking changes; prefer adding fields and endpoints.
  • Pick one scheme: URLPathVersioning (most common), AcceptHeaderVersioning, QueryParameterVersioning, HostNameVersioning or NamespaceVersioning.
  • Use DEFAULT_VERSIONING_CLASS, ALLOWED_VERSIONS and DEFAULT_VERSION; read request.version to choose serializers or behaviour.
  • Use DRF's reverse() with request so generated links keep the version.
  • Share models and business logic across versions, deprecate with headers and dates, and retire old versions deliberately.

Next: OpenAPI Schema Generation