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.
REST_FRAMEWORK = {
'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning'
}You can also set the versioning scheme on an individual view.
from rest_framework.versioning import URLPathVersioning
from rest_framework.views import APIView
class ProfileList(APIView):
versioning_class = URLPathVersioningBuilt-in Versioning Schemes
AcceptHeaderVersioning
This scheme expects the client to specify the version as part of the media type in the Accept header.
GET /bookings/ HTTP/1.1
Host: example.com
Accept: application/json; version=1.0URLPathVersioning
This scheme requires the version to be specified as part of the URL path.
GET /v1/bookings/ HTTP/1.1
Host: example.com
Accept: application/jsonYour URL conf must include a pattern that matches the version with a version keyword argument:
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.
# 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.
GET /bookings/ HTTP/1.1
Host: v1.example.com
Accept: application/jsonQueryParameterVersioning
This scheme specifies the version as a query parameter in the URL.
GET /something/?version=0.1 HTTP/1.1
Host: example.com
Accept: application/jsonReversing 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.
from rest_framework.reverse import reverse
def get(self, request):
url = reverse('bookings-list', request=request)
return Response({'bookings_url': url})