Article 021
Production Evaluation of django-api-versioning
Evaluate django-api-versioning through route inheritance, version isolation, lifecycle handling, routing inspection, and regression tests.
Package disclosure: The author is the creator, owner, and maintainer of
django-api-versioning.
A production API versioning strategy needs more than a version number in a URL. The application must resolve each version to the intended view, preserve older response contracts, expose a predictable routing structure, and manage the eventual retirement of older versions.
This article evaluates those requirements through django-api-versioning. Rather than treating versioned routing as a collection of manually maintained URL patterns, it examines how the package's declarative registration model works, what it automates, and which production responsibilities remain with the application. For release-specific requirements, consult the package metadata and changelog. For actual compatibility results, inspect workflow runs for the exact source commit.
The package provides:
- Declarative endpoint registration for function-based and supported class-based views, plus the optional
VersionedRouterintegration for DRF ViewSets. - Version-range registration and explicit version selection.
- Route inheritance when a new API version is introduced.
- Version-aware reverse lookup.
- Routing inspection and strict snapshot-based regression protection.
- Optional
VersionedRouterintegration for DRFSimpleRouterViewSets, including per-generated-route inheritance and version-aware reversal. - Configurable version-wide lifecycle middleware for deprecation headers and sunset enforcement.
- Explicit endpoint removal and endpoint-level lifecycle declarations, available since 1.2.0.
Scope: routing, ViewSet version selection, and lifecycle metadata. The decorator-based @endpoint API does not configure a DRF versioning class or automatically populate DRF's request.version; the optional VersionedRouterVersioning adapter does so for ViewSets registered through VersionedRouter. The package does not enforce semantic backward compatibility, coordinate client migrations, or replace application-level contract tests.
Package-specific behavior described in this article is documented in the project's canonical routing contract and source code.
Install the package from PyPI.
1. Start with the routing model
The package's central abstraction is a versioned endpoint declaration:
from django_api_versioning import endpointThe decorator registers a view against a resource path and one or more API versions. The package then builds Django URL patterns from those declarations.
With the default configuration:
API_BASE_PATH = "api/v{version}/"
API_MIN_VERSION = 1
API_MAX_VERSION = 2this declaration:
@endpoint("users/", version=1, view_name="user-list")
class UserListView(ListAPIView):
...produces these versioned paths:
/api/v1/users/
/api/v2/users/The path is derived from three elements:
API_BASE_PATH, formatted with the integer version.- The optional
app_namesegment. - The endpoint's
postfix, here"users/".
The Python class name does not determine the URL path or URL name. Use view_name when the route needs an explicit Django URL pattern name.
The package's registration rules, import paths, version identifiers, route construction, and ViewSet boundary are documented in the canonical versioning contract. That document is the reference for package-specific routing semantics used throughout this article.
2. Route inheritance and version-specific implementations
A production routing design should make it clear which implementation handles a request for each supported version.
Register a new implementation without duplicating every route
Consider an API with two versions of the users endpoint:
from django_api_versioning import endpoint
from rest_framework.generics import ListAPIView
from .models import User
from .serializers import UserSerializerV1, UserSerializerV2
@endpoint("users/", version=1, view_name="user-list")
class UserListV1(ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializerV1
@endpoint("users/", version=2, view_name="user-list")
class UserListV2(ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializerV2With API_MIN_VERSION = 1 and API_MAX_VERSION = 2, the routing matrix is:
| Request | Registered handler |
|---|---|
/api/v1/users/ | UserListV1 |
/api/v2/users/ | UserListV2 |
The declarations use the same postfix and view_name, but different source versions. The newer declaration replaces the older implementation for v2. The v1 route continues to use UserListV1.
This is route-registration inheritance, not Python class inheritance. The registry selects which view callable is attached to each generated URL. It does not create subclasses, merge serializers, or copy methods between views.
The inheritance traversal rule
For a request to version N, the effective implementation is the registered implementation with the highest source version that is less than or equal to N.
This is a way to calculate the effective mapping in the registry, not a request-time backward search. The package expands the declarations into concrete URL patterns when endpoint modules are imported; requests then match those generated patterns directly.
For example, consider these declarations:
@endpoint("orders/", version=1, view_name="order-list")
def order_list_v1(request):
return JsonResponse({"implementation": "v1"})
@endpoint("orders/", version=3, view_name="order-list")
def order_list_v3(request):
return JsonResponse({"implementation": "v3"})With API_MIN_VERSION = 1 and API_MAX_VERSION = 4, the effective routing matrix is:
| Requested version | Handler |
|---|---|
| v1 | order_list_v1 |
| v2 | order_list_v1 |
| v3 | order_list_v3 |
| v4 | order_list_v3 |
Now:
- A request to v1 resolves to
order_list_v1. - A request to v2 resolves to
order_list_v1. - A request to v3 resolves to
order_list_v3. - A request to v4 resolves to
order_list_v3.
The explicit routing matrix matters: inheritance through an unchanged version and replacement by a newer declaration are different cases.
Release a new version without changing every endpoint
Suppose the application initially has:
API_MIN_VERSION = 1
API_MAX_VERSION = 2and an endpoint registered with version=1.
When the application introduces v3, increasing the maximum:
API_MAX_VERSION = 3extends that endpoint's registration to v3. The existing implementation continues to serve the new version unless a newer declaration overrides it.
This is useful when a new API version is introduced but most endpoints retain their existing contracts. Only endpoints that need a different implementation require new declarations.
The alternative is not necessarily duplicating business logic. A manually maintained URL configuration can point several versioned paths to the same view. The package's benefit is reducing repeated registration declarations and making the effective version-to-view mapping explicit in a central registry.
Distinguish a missing endpoint from a missing API version
Explicit version registration is available when an endpoint should exist only in selected versions:
@endpoint(
"reports/",
versions=[1, 3],
view_name="report-list",
)
def report_list(request):
return JsonResponse({"reports": []})This registers the endpoint for v1 and v3, but not v2.
There are two different situations to distinguish:
- The API version does not exist in the configured range. For example, v4 is outside a configuration whose maximum is 3.
- The API version exists, but this endpoint is not registered for it. In the example above, v2 exists as an API version, but the reports endpoint has no v2 route.
A request to an unregistered endpoint/version combination does not become valid merely because the API version itself is supported.
Use version=N for a continuous segment of versions and versions=[...] when the endpoint must exist only in explicitly selected versions.
3. Version isolation is an application responsibility
Route selection does not guarantee response-contract isolation.
For example, separate serializers allow an application to evolve a response:
class UserSerializerV1(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "name"]
class UserSerializerV2(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "name", "display_name"]The v2 view can use UserSerializerV2 while v1 continues to use UserSerializerV1.
However, separate serializer classes do not isolate shared dependencies. Changes to a model field, permission class, shared base class, or utility function can still affect both versions.
A useful project structure is to keep version-specific API code organized explicitly:
api/
v1/
serializers.py
views.py
v2/
serializers.py
views.pyThis is an application organization convention, not a directory structure required by the package. @endpoint connects the version-specific view implementations to the generated routing structure.
For each version, test the actual response contract. Review changes to shared dependencies and database schemas while older versions remain active.
4. Supported view types and the DRF ViewSet boundary
The package supports function-based views and supported Django class-based views, including DRF's APIView and GenericAPIView.
A DRF ViewSet class is different. It requires an action mapping when converted into a view callable. The package's registry calls as_view() on a class without supplying that mapping, so decorating a ModelViewSet class directly with @endpoint is not supported.
For resource-oriented ViewSets, use the package's optional VersionedRouter integration when you want the package registry to manage version-specific implementations and inherit unchanged generated routes. It delegates URL generation to DRF's SimpleRouter and registers each generated pattern with the version registry:
from django_api_versioning.routers import VersionedRouter
from users.views import UserViewSetV1, UserViewSetV2
router = VersionedRouter()
router.register("users", UserViewSetV1, version=1, basename="user")
router.register("users", UserViewSetV2, version=2, basename="user")
urlpatterns = router.urlsConfigure VersionedRouterVersioning as DRF's default versioning class, or on selected ViewSets, when the application needs request.version, reverse_action(), or version-aware hyperlinked serializer URLs. The adapter reads the concrete version namespace created by the router.
A manually configured callable such as:
UserViewSet.as_view({"get": "list"})can still be registered for one individual route with @endpoint. It is not automatic router integration and does not replace the router-generated list, detail, and custom-action routes.
Plain DRF SimpleRouter and DefaultRouter instances remain valid alternatives when the application wants to manage each version's URL configuration itself. They remain outside this package's registry. VersionedRouter supports SimpleRouter behavior; it does not claim DefaultRouter API-root or format-suffix parity.
These are deliberate boundaries of the integration model. See the Versioned DRF ViewSet guide and the canonical routing contract.
5. Reverse lookup and request version
Generate a URL for a specific version
The package provides api_reverse() for version-aware URL generation:
from django_api_versioning import api_reverse
url = api_reverse("user-list", version=2)The endpoint must have been registered with the corresponding view_name.
When multiple matching versions exist and no version is supplied, the package raises AmbiguousVersionError. This avoids silently selecting one of several registered versioned routes.
If no matching route exists, api_reverse() raises Django's NoReverseMatch.
Use an explicit version when the application needs a deterministic version-specific URL.
Do not assume that request.version is populated
The package registers version-specific URL patterns. Its @endpoint decorator does not itself populate DRF's request.version; this section describes decorator-registered views, not the separate VersionedRouterVersioning adapter for ViewSets.
A request to /api/v1/users/ can resolve to the v1 view without request.version being set.
DRF's URLPathVersioning expects a URL keyword argument named version. The package's default static paths, such as /api/v1/users/, are not dynamic URL patterns containing <int:version>.
If application code needs request.version, configure a compatible extraction mechanism and test it against the actual URL patterns. Do not assume that enabling URLPathVersioning alone is sufficient.
The distinction is:
- The decorator-based
@endpointAPI selects the registered view through its generated URL patterns. - DRF's versioning scheme determines how a request version is extracted and exposed through
request.versionfor decorator-registered views. - For ViewSets,
VersionedRouterVersioningis the package-provided adapter that reads the concreteVersionedRouternamespace and exposes it throughrequest.version.
6. Inspect and protect the routing matrix
Declarative registration is more useful in production when the effective routing configuration can be inspected and reviewed.
Inspect registered routes
The package provides the check_versions management command:
python manage.py check_versionsIt displays the registered routing matrix, including the route and the view callback associated with each version. It also warns when a route has gaps within the configured version range.
For example, an endpoint explicitly registered for v1 and v3 may produce a warning for v2. That warning is evidence to review, not necessarily a defect: the omission may be intentional.
The command resolves and imports the project's root URLconf before inspecting the registry. This executes endpoint-module imports referenced by that URLconf and includes routes registered through VersionedRouter. A forgotten import can therefore result in an incomplete matrix or an empty-registry failure when --fail-on-empty is used. The command does not discover arbitrary Python modules that are not imported by application startup or the URLconf.
If your application deliberately imports declaration modules from an app's AppConfig.ready(), that remains a valid project-level organization choice. Ensure those imports are safe during Django startup and do not perform database queries in ready().
# api/apps.py
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = "api"
def ready(self):
from . import views # noqa: F401Use this only when importing those views during app startup is safe for your project; do not perform database queries in ready(). Ensure INSTALLED_APPS references the config class.
Protect the routing configuration with a snapshot
The package also provides assert_version_matrix() through django_api_versioning.testing.
First, generate the initial snapshot deliberately:
from django_api_versioning.testing import assert_version_matrix
assert_version_matrix(
snapshot=".version_matrix.json",
update=True,
)Review the generated file and commit it to version control.
Then use the assertion in the test suite:
from importlib import import_module
from django.conf import settings
from django_api_versioning.testing import assert_version_matrix
def test_version_matrix():
import_module(settings.ROOT_URLCONF)
assert_version_matrix(snapshot=".version_matrix.json", strict=True)If the current routing matrix differs from the committed snapshot, the assertion raises VersionMatrixError and reports the differences.
For backward compatibility, the default non-strict mode can create a missing snapshot. In CI, use strict=True so an empty registry or missing committed baseline fails instead of silently creating one. Generate the initial snapshot deliberately with update=True, review and commit it, then keep update=True out of the regular test. The strict assertion protects the approved routing matrix; it does not prove response-schema or business compatibility.
The snapshot protects route registration, not response semantics. It cannot prove that serializers, permissions, filtering, pagination, or business behavior remain compatible.
7. API lifecycle handling
Routing and lifecycle management are related, but they are not the same responsibility.
An application may need to communicate that a version is deprecated and eventually reject requests to it. The relevant HTTP standards include RFC 9745 for the Deprecation response header and RFC 8594 for the Sunset HTTP header.
django-api-versioning provides LifecycleMiddleware and the API_VERSION_LIFECYCLE setting for configured lifecycle behavior. See the lifecycle implementation and canonical routing contract for the current behavior and configuration rules.
For example, an application can define lifecycle metadata:
# settings.py
API_VERSION_LIFECYCLE = {
1: {
"status": "deprecated",
"deprecated_at": "2026-12-01T00:00:00+00:00",
"sunset": "2027-06-30",
},
2: {
"status": "active",
},
}Add the middleware to Django's MIDDLEWARE setting:
MIDDLEWARE = [
# Other middleware
"django_api_versioning.lifecycle.LifecycleMiddleware",
]Replace the date placeholder with the actual planned sunset date before deployment.
The middleware can identify the version from the request and, when necessary, extract it from the package's static URL path. It does not require DRF's request.version to be populated for that path-based extraction.
The lifecycle behavior has important details:
- A version with
status: "deprecated"and a validdeprecated_atvalue receives a date-valuedDeprecationresponse header. - If a sunset date is configured for that deprecated version, the middleware also sends a
Sunsetheader. - A
deprecatedlifecycle entry must includedeprecated_atas an ISO 8601 date or datetime. The middleware emits it as the RFC 9745 date-valued Structured Field, not as the legacyDeprecation: truevalue. - When the configured sunset date has passed, the middleware returns
410 Gone. - A
retiredstatus by itself does not trigger410 Gone; the configured sunset date must have passed. - A
retiredversion with a future sunset date is still served and carries theSunsetheader, plusDeprecationwhendeprecated_atis configured.
The middleware implements technical lifecycle behavior. The application team still owns the retirement policy, date selection, client communication, usage monitoring, and migration plan.
Endpoint-level lifecycle (available since 1.2.0)
Version 1.2.0 extends lifecycle metadata from whole API versions to individual registered endpoint versions. Use set_endpoint_lifecycle() with decorator-registered endpoints or VersionedRouter.set_lifecycle() for generated ViewSet operations. Declarations can be scoped to an HTTP method or DRF action. Matching responses receive the applicable RFC 9745 Deprecation and RFC 8594 Sunset headers; when an endpoint's sunset date passes, this endpoint-level policy remains headers-only and does not itself remove the route or return 410. Version-wide past-Sunset enforcement remains separate and continues to return 410 for the version.
Projects using drf-spectacular can opt into EndpointLifecycleAutoSchema to mark the corresponding OpenAPI operation as deprecated. drf-spectacular is optional; neither it nor the repository's OpenAPI consumer example is a core runtime dependency. These APIs are included in the published 1.2.0 package.
8. Version discovery and API documentation
A versioned routing system should not make clients guess which versions or endpoints are available.
An application may expose a discovery endpoint such as /api/versions/, but it should not blindly report every integer between API_MIN_VERSION and API_MAX_VERSION as an endpoint-level capability.
For example:
@endpoint(
"reports/",
versions=[1, 3],
view_name="report-list",
)
def report_list(request):
return JsonResponse({"reports": []})The configured range may include v2, but this endpoint is not registered for v2.
If clients need endpoint-level discovery, derive the response from a verified routing matrix or maintain an explicit application-level policy. The package's routing registry should not be treated as a public version-discovery endpoint; implement discovery at the application level when clients require it.
API documentation is a separate concern as well. Tools such as drf-spectacular and drf-yasg generate API documentation. Registering multiple URL patterns does not automatically guarantee correctly separated OpenAPI documents for each version.
Configure and test the documentation tool for the version-specific schemas the application intends to publish.
9. URLconf integration and migration
The package's decorators register routes when the modules containing them are imported. Import those modules before importing the package's URL patterns.
For example:
# project/urls.py
from django.urls import include, path
from accounts import views as account_views
from django_api_versioning.urls import urlpatterns as api_urlpatterns
urlpatterns = [
path("", include(api_urlpatterns)),
]The account_views import is intentional: importing the module executes its endpoint declarations and populates the registry. The package's exported urlpatterns references the registry's shared list rather than a copy, so importing that list before the view module does not permanently capture an empty snapshot. Keep imports explicit and ensure registration is complete before request resolution.
For an existing application, a migration should compare the previous URL configuration with the generated routing matrix:
- Identify the existing version-to-view mapping.
- Add
@endpointdeclarations to the relevant views. - Import the declaration modules before the package URL patterns.
- Inspect the generated matrix with
check_versions. - Compare representative requests and response contracts across supported versions.
- Commit a routing snapshot if the project needs regression protection.
A migration is not complete merely because Django starts successfully. Existing URLs, reverse lookup behavior, response contracts, and permissions must continue to match the application's intended behavior.
10. Trade-offs and scope
The package's main benefit is declarative route registration with explicit version inheritance. It reduces repeated registration declarations when endpoints remain unchanged across API versions and makes the effective routing matrix inspectable.
That benefit comes with a responsibility: a declaration using version=N carries the implementation forward through API_MAX_VERSION. If an endpoint's contract changes, the team must decide whether to add a newer implementation or use explicit version registration.
A newer implementation does not retroactively fix older overrides. If v2 has its own implementation, changing the v1 implementation does not replace the v2 route.
The package also does not:
- Enforce backward compatibility between serializers, views, or database schemas.
- Populate DRF's
request.versionfor decorator-based@endpointviews without a separately configured DRF versioning class; useVersionedRouterVersioningfor ViewSets. - Decorate DRF ViewSet classes directly with
@endpoint; useVersionedRouterfor package-managed DRFSimpleRouterroute generation and@actionintegration. Plain DRFSimpleRouterandDefaultRouterinstances remain manual alternatives outside the package registry. - Generate separate OpenAPI schemas for every API version.
- Provide a built-in version-discovery endpoint.
- Decide deprecation policy or coordinate client migration.
- Guarantee deployment safety or rollback.
When the benefit is smaller: if an API has very few versioned endpoints, rarely introduces new versions, and its existing URL configuration is already straightforward to maintain, adopting a separate registration model may add more complexity than it removes.
The useful evaluation is not whether the package replaces every part of API versioning. It is whether declarative registration, route inheritance, version-aware reverse lookup, routing inspection, regression protection, and configured lifecycle behavior address the specific maintenance problems in the application.
11. Production verification checklist
Use this checklist when integrating django-api-versioning into a production project:
| Area | Verification |
|---|---|
| Version registration | Each declaration generates the intended versioned paths |
| Route inheritance | Requests resolve to the expected source-version implementation |
| Explicit versions | Endpoints are absent from versions not listed in versions=[...] |
| Version boundaries | API_MIN_VERSION and API_MAX_VERSION match the intended release range |
| View support | The registered callable is a supported function or class-based view |
| ViewSet boundary | Register through VersionedRouter for package-managed per-route inheritance, or use plain DRF routers for manual routing |
| URL construction | The generated path matches API_BASE_PATH, app_name, and postfix |
| Reverse lookup | api_reverse() generates the intended version-specific URL |
| Request version | Any required request.version extraction is configured and tested |
| Contract isolation | Each version returns the intended response fields and behavior |
| Lifecycle headers | Version-wide and endpoint-level lifecycle declarations produce the intended headers |
| Sunset enforcement | Version-wide past-Sunset requests receive 410; endpoint-level past-Sunset policy is headers-only |
| Routing inspection | check_versions output has been reviewed |
| Routing regression | The approved version matrix snapshot is committed and checked in CI |
| Documentation | Each published OpenAPI document describes the intended version |
| Migration | Existing URLs and response contracts remain correct |
| Deployment | Version rollout, client migration, retirement, and rollback have defined owners |
The package supplies concrete mechanisms for the routing-related rows. The remaining application and operational requirements need their own implementation and tests.
Next step
If your project uses Django and DRF and its versioned URL registrations are becoming repetitive, evaluate the package's registration model against your current route matrix. Start with the django-api-versioning repository, review the canonical routing contract, and verify the generated matrix before migrating production routes.