Skip to content

Versioning

API versioning allows you to alter behavior between different clients. DRF provides for a number of different versioning schemes.

Versioning is determined based on the incoming client request, and may dictate the format of the request or response, or which view logic is executed.

Configuring the Versioning Scheme

The default versioning scheme may be set globally in settings.py.

python
REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
}

You can also set the versioning scheme on an individual view.

python
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView

class ProfileList(APIView):
    versioning_class = URLPathVersioning

Built-in Versioning Schemes

AcceptHeaderVersioning

This scheme expects the client to specify the version as part of the media type in the Accept header.

http
GET /bookings/ HTTP/1.1
Host: example.com
Accept: application/json; version=1.0

URLPathVersioning

This scheme requires the version to be specified as part of the URL path.

http
GET /v1/bookings/ HTTP/1.1
Host: example.com
Accept: application/json

Your URL conf must include a pattern that matches the version with a version keyword argument:

python
urlpatterns = [
    re_path(r'^(?P<version>(v1|v2))/bookings/$', bookings_list, name='bookings-list'),
]

NamespaceVersioning

To the client, this scheme is the same as URLPathVersioning. However, it uses Django's URL namespaces to determine the requested version.

python
# urls.py
urlpatterns = [
    path('v1/', include('bookings.urls', namespace='v1')),
    path('v2/', include('bookings.urls', namespace='v2')),
]

HostNameVersioning

This scheme requires the client to specify the requested version as part of the hostname in the URL.

http
GET /bookings/ HTTP/1.1
Host: v1.example.com
Accept: application/json

QueryParameterVersioning

This scheme specifies the version as a query parameter in the URL.

http
GET /something/?version=0.1 HTTP/1.1
Host: example.com
Accept: application/json

Reversing URLS

When using versioning, you should use DRF's reverse function to construct URLs, as it will automatically incorporate the current version into the generated URL.

python
from rest_framework.reverse import reverse

def get(self, request):
    url = reverse('bookings-list', request=request)
    return Response({'bookings_url': url})