From 42ef9b77381c2823f793b74a6e55c23a6e64afbc Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:10 +0400 Subject: [PATCH 01/49] feat: implement explicit endpoint removal --- README.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fbcc049d..13146eb5 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,13 @@ Django API Versioning makes that mapping explicit with `@endpoint`: This is inheritance of route registrations, not automatic backward compatibility. Your application remains responsible for response schemas, business behavior, and compatibility tests. +When an endpoint must stop existing in a later version, declare that explicitly +with `remove_endpoint("orders/", from_version=3)`. The route remains available +in earlier versions, disappears from the removed version onward, and can be +reintroduced by a later version declaration. For DRF, use +`VersionedRouter.remove(prefix, route_name, from_version=...)` to remove one +generated action without removing the rest of its ViewSet. + ## Why use it with Django REST Framework? DRF already provides request-version identification and ViewSet route generation. Django API Versioning adds the missing connection between those capabilities: **mapping each concrete API version to the correct ViewSet implementation while inheriting unchanged routes independently**. @@ -174,8 +181,6 @@ pip install "djangorestframework>=3.18.3,<3.19" See the [Versioned DRF ViewSet guide](https://mojtaba-arvin.github.io/django-api-versioning/articles/025-django-api-versioning-viewset-support-limitations/) for route inheritance, reversal, namespaces, and the exact integration boundary. -For an optional, executable OpenAPI workflow, see the [versioned OpenAPI contract example](https://github.com/mojtaba-arvin/django-api-versioning/tree/main/examples/openapi_contract). It demonstrates per-version drf-spectacular generation and serializer introspection; it does not make drf-spectacular or oasdiff runtime dependencies. - ## Requirements - Python 3.10+ From 6cfd43eccf0e9c51215f89af121d04bfa1f60f43 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:12 +0400 Subject: [PATCH 02/49] feat: implement explicit endpoint removal --- django_api_versioning/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/django_api_versioning/__init__.py b/django_api_versioning/__init__.py index 8a22774a..f2d8f0f5 100644 --- a/django_api_versioning/__init__.py +++ b/django_api_versioning/__init__.py @@ -1,4 +1,4 @@ -from .decorators import endpoint, ver_range +from .decorators import endpoint, remove_endpoint, ver_range from .reverse import api_reverse -__all__ = ["endpoint", "ver_range", "api_reverse"] +__all__ = ["endpoint", "remove_endpoint", "ver_range", "api_reverse"] From 4bb51083d96c1943f92cc6a303a1f242de288070 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:15 +0400 Subject: [PATCH 03/49] feat: implement explicit endpoint removal --- django_api_versioning/decorators.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/django_api_versioning/decorators.py b/django_api_versioning/decorators.py index de50847a..2176d897 100644 --- a/django_api_versioning/decorators.py +++ b/django_api_versioning/decorators.py @@ -139,3 +139,21 @@ def _validate_version(version: int, max_version: int) -> None: raise InvalidVersionError( f"Version {version} is above the maximum allowed version {max_version}." ) + + +def remove_endpoint( + postfix: str, + *, + from_version: int, + app_name: str | None = None, +) -> None: + """Remove a logical endpoint from a version onward. + + A later declaration with a higher source version can reintroduce it. + """ + if not isinstance(postfix, str): + raise TypeError("postfix must be a string.") + if postfix.startswith("/"): + raise VersioningError("postfix must be relative and must not start with '/'.") + app_name_part = f"{app_name}/" if app_name else "" + registry.remove(f"{app_name_part}{postfix}", from_version) From ed572724d8122260db6c76ba1896e99dc8b4d729 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:26 +0400 Subject: [PATCH 04/49] feat: implement explicit endpoint removal --- django_api_versioning/management/commands/check_versions.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/django_api_versioning/management/commands/check_versions.py b/django_api_versioning/management/commands/check_versions.py index 04d242a7..9a052054 100644 --- a/django_api_versioning/management/commands/check_versions.py +++ b/django_api_versioning/management/commands/check_versions.py @@ -2,7 +2,7 @@ from django.core.management.base import BaseCommand, CommandError -from ...registry import registry +from ...registry import REMOVED_ROUTE, registry from ...testing import _load_root_urlconf @@ -52,6 +52,8 @@ def handle(self, *args, **options): @staticmethod def _get_callback_name(callback): """Resolve callback name, handling both functions and class-based views.""" + if callback is REMOVED_ROUTE: + return "" # Try to get from class-based view metadata first if hasattr(callback, "view_class"): return callback.view_class.__name__ From e87193ac6ca6ed5d5daa56f446e8ae342924e08b Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:29 +0400 Subject: [PATCH 05/49] feat: implement explicit endpoint removal --- django_api_versioning/registry.py | 111 ++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/django_api_versioning/registry.py b/django_api_versioning/registry.py index 4c5e7c88..78b761f3 100644 --- a/django_api_versioning/registry.py +++ b/django_api_versioning/registry.py @@ -4,6 +4,11 @@ from django.urls import URLPattern, path from django.views import View +from .exceptions import InvalidVersionError, VersionRangeError, VersionTypeError +from .settings import api_settings + +REMOVED_ROUTE = object() + ViewType = Callable[..., HttpResponse] | type[View] @@ -16,6 +21,73 @@ class UrlRegistry: def __init__(self) -> None: self.urlpatterns: list[URLPattern] = [] + self._removal_boundaries: dict[str, set[int]] = {} + self._removed_patterns: dict[tuple[str, int], URLPattern] = {} + + def clear(self) -> None: + """Clear active routes and removal declarations.""" + self.urlpatterns.clear() + self._removal_boundaries.clear() + self._removed_patterns.clear() + + def remove(self, logical_endpoint: str, from_version: int) -> None: + """Suppress an endpoint from a concrete version until reintroduced.""" + if not isinstance(logical_endpoint, str) or not logical_endpoint: + raise TypeError("logical_endpoint must be a non-empty string.") + if isinstance(from_version, bool) or not isinstance(from_version, int): + raise VersionTypeError("Removal version must be an integer.") + if from_version > api_settings.API_MAX_VERSION: + raise InvalidVersionError( + f"Removal version {from_version} is above the maximum allowed " + f"version {api_settings.API_MAX_VERSION}." + ) + if from_version < api_settings.API_MIN_VERSION: + raise VersionRangeError( + f"Removal version {from_version} is below the minimum allowed " + f"version {api_settings.API_MIN_VERSION}." + ) + + self._removal_boundaries.setdefault(logical_endpoint, set()).add(from_version) + + for index in range(len(self.urlpatterns) - 1, -1, -1): + pattern = self.urlpatterns[index] + if getattr(pattern, self._LOGICAL_ENDPOINT_ATTR, None) != logical_endpoint: + continue + route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) + source_version = getattr(pattern, self._SOURCE_VERSION_ATTR, None) + if route_version is None or route_version < from_version: + continue + if source_version is not None and source_version > from_version: + continue + self._removed_patterns[(logical_endpoint, route_version)] = pattern + del self.urlpatterns[index] + + def _removal_boundary( + self, + logical_endpoint: str | None, + route_version: int | None, + ) -> int | None: + if logical_endpoint is None or route_version is None: + return None + boundaries = self._removal_boundaries.get(logical_endpoint, set()) + applicable = [boundary for boundary in boundaries if boundary <= route_version] + return max(applicable) if applicable else None + + def _is_suppressed( + self, + logical_endpoint: str | None, + route_version: int | None, + source_version: int | None, + ) -> bool: + boundary = self._removal_boundary(logical_endpoint, route_version) + return boundary is not None and ( + source_version is None or source_version <= boundary + ) + + def _record_removed(self, pattern: URLPattern, logical_endpoint: str) -> None: + route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) + if route_version is not None: + self._removed_patterns[(logical_endpoint, route_version)] = pattern def register( self, @@ -41,6 +113,23 @@ def register( if logical_endpoint is not None: setattr(pattern, self._LOGICAL_ENDPOINT_ATTR, logical_endpoint) + if self._is_suppressed(logical_endpoint, route_version, source_version): + if route_index is not None: + existing = self.urlpatterns[route_index] + existing_logical = getattr(existing, self._LOGICAL_ENDPOINT_ATTR, None) + existing_version = getattr(existing, self._ROUTE_VERSION_ATTR, None) + existing_source = getattr(existing, self._SOURCE_VERSION_ATTR, None) + if self._is_suppressed( + existing_logical, existing_version, existing_source + ): + del self.urlpatterns[route_index] + if logical_endpoint is not None: + self._record_removed(pattern, logical_endpoint) + return + + if logical_endpoint is not None and route_version is not None: + self._removed_patterns.pop((logical_endpoint, route_version), None) + if route_index is None: self.urlpatterns.append(pattern) else: @@ -78,6 +167,21 @@ def register_urlpattern( if logical_endpoint is not None: setattr(pattern, self._LOGICAL_ENDPOINT_ATTR, logical_endpoint) + if self._is_suppressed(logical_endpoint, route_version, source_version): + if route_index is not None: + existing = self.urlpatterns[route_index] + existing_logical = getattr(existing, self._LOGICAL_ENDPOINT_ATTR, None) + existing_version = getattr(existing, self._ROUTE_VERSION_ATTR, None) + existing_source = getattr(existing, self._SOURCE_VERSION_ATTR, None) + if self._is_suppressed(existing_logical, existing_version, existing_source): + del self.urlpatterns[route_index] + if logical_endpoint is not None: + self._record_removed(pattern, logical_endpoint) + return + + if logical_endpoint is not None and route_version is not None: + self._removed_patterns.pop((logical_endpoint, route_version), None) + if route_index is None: self.urlpatterns.append(pattern) else: @@ -109,6 +213,11 @@ def get_version_matrix(self) -> dict[str, dict[int | None, Callable]]: route = str(pattern.pattern) route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) matrix.setdefault(route, {})[route_version] = pattern.callback + for (_, route_version), pattern in self._removed_patterns.items(): + tombstone_path = str(pattern.pattern) + matrix.setdefault(tombstone_path, {}).setdefault( + route_version, REMOVED_ROUTE + ) return matrix def get_logical_version_matrix(self) -> dict[str, dict[int | None, Callable]]: @@ -127,6 +236,8 @@ def get_logical_version_matrix(self) -> dict[str, dict[int | None, Callable]]: ) route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None) matrix.setdefault(logical_id, {})[route_version] = pattern.callback + for (logical_id, route_version), _pattern in self._removed_patterns.items(): + matrix.setdefault(logical_id, {})[route_version] = REMOVED_ROUTE return matrix def _find_route_index(self, route: str) -> int | None: From fb5b04b74ef4d89be8d2cd98b87093f3616848cd Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:31 +0400 Subject: [PATCH 06/49] feat: implement explicit endpoint removal --- django_api_versioning/routers.py | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/django_api_versioning/routers.py b/django_api_versioning/routers.py index bc873cc3..75c1f257 100644 --- a/django_api_versioning/routers.py +++ b/django_api_versioning/routers.py @@ -11,7 +11,8 @@ try: from rest_framework.exceptions import NotFound - from rest_framework.versioning import NamespaceVersioning + from rest_framework.routers import SimpleRouter + from rest_framework.versioning import BaseVersioning except ImportError as exc: # pragma: no cover - exercised without optional DRF raise ImportError( "VersionedRouter requires Django REST Framework. Install a DRF release " @@ -129,6 +130,18 @@ def register( route_version=route_version, ) + def remove(self, prefix: str, route_name: str, *, from_version: int) -> None: + """Remove one logical DRF route from a concrete version onward. + + route_name is the URL name generated from the registration basename + and action (for example, "order-archive"), not a regex pattern. + """ + if not isinstance(prefix, str) or not prefix: + raise VersioningError("prefix must be a non-empty string.") + if not isinstance(route_name, str) or not route_name: + raise VersioningError("route_name must be a non-empty string.") + registry.remove(f"{prefix}:{route_name}", from_version) + @staticmethod def _validate_version(version: int) -> None: if isinstance(version, bool) or not isinstance(version, int): @@ -147,11 +160,6 @@ def _register_version( source_version: int | None, route_version: int | None, ) -> None: - # Import lazily: DRF's SimpleRouter imports APIView, which resolves - # DEFAULT_VERSIONING_CLASS. Importing it at module load time would - # recurse while DRF is trying to import VersionedRouterVersioning. - from rest_framework.routers import SimpleRouter - route_prefix = prefix if route_version is not None: route_prefix = ( @@ -227,7 +235,7 @@ def urls(self) -> list[URLPattern | URLResolver]: return urlpatterns -class VersionedRouterVersioning(NamespaceVersioning): +class VersionedRouterVersioning(BaseVersioning): """Expose the router-selected version through DRF's request.version. The router namespaces each concrete version as vN. This adapter reads @@ -285,8 +293,8 @@ def reverse( format: str | None = None, **extra: Any, ) -> str: - # NamespaceVersioning.reverse() calls our get_versioned_viewname(). - # Do not pre-qualify the name here or the namespace would be applied twice. + if request is not None: + viewname = self.get_versioned_viewname(viewname, request) return super().reverse( viewname, args=args, From e0795694b0ab8fa46e8584a1483e92ce16af5f29 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:44 +0400 Subject: [PATCH 07/49] feat: implement explicit endpoint removal --- django_api_versioning/testing.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/django_api_versioning/testing.py b/django_api_versioning/testing.py index c790b07b..282aea9d 100644 --- a/django_api_versioning/testing.py +++ b/django_api_versioning/testing.py @@ -5,7 +5,7 @@ from django.urls.resolvers import URLResolver from .exceptions import VersionMatrixError -from .registry import registry +from .registry import REMOVED_ROUTE, registry def _load_root_urlconf() -> None: @@ -48,6 +48,8 @@ def build_version_matrix() -> dict: def _callback_name(callback: object) -> str: """Return a stable display name for function, class-based, or callable views.""" + if callback is REMOVED_ROUTE: + return "" view_class = getattr(callback, "view_class", None) if view_class is not None: return view_class.__name__ From 3dbb20efd63f71f421657fb5c037f13e76cb2f5f Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:46 +0400 Subject: [PATCH 08/49] feat: implement explicit endpoint removal --- docs/design/endpoint-removal.md | 94 +++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 docs/design/endpoint-removal.md diff --git a/docs/design/endpoint-removal.md b/docs/design/endpoint-removal.md new file mode 100644 index 00000000..5c890e89 --- /dev/null +++ b/docs/design/endpoint-removal.md @@ -0,0 +1,94 @@ +# Explicit endpoint removal and reintroduction + +**Status:** Implementation in progress +**Runtime policy:** Removed endpoint routes are absent and resolve to 404 +**Scope:** Django-native endpoints and DRF VersionedRouter routes + +## Problem + +Forward route inheritance intentionally carries unchanged registrations into later API versions. It currently has no explicit inverse operation: omitting an endpoint from a later declaration does not remove the inherited route. + +Removal must be a first-class declaration, not an accidental side effect of missing imports or manual URLPattern mutation. + +## Public API proposal + +For decorator-registered Django endpoints: + +~~~python +from django_api_versioning import endpoint, remove_endpoint + +@endpoint("orders/", version=1, view_name="orders") +def orders_v1(request): + ... + +remove_endpoint("orders/", from_version=3) +~~~ + +For DRF ViewSets, target one generated route by its stable URL name: + +~~~python +router = VersionedRouter() +router.register("orders", OrderViewSetV1, version=1, basename="order") +router.remove("orders", "order-archive", from_version=3) +~~~ + +The DRF route name is the URL name generated from the basename and action. The logical identity is router prefix plus route name; it is not the generated regex string. + +## Segment semantics + +A removal declaration at version N suppresses an earlier source declaration from N through API_MAX_VERSION. A later registration with source_version greater than N explicitly reintroduces the route from that version onward. + +Examples: + +| Version | v1 declaration | Removal from v3 | Reintroduced at v4 | +| --- | --- | --- | --- | +| v1 | active | active | active | +| v2 | inherited | inherited | inherited | +| v3 | inherited | removed | removed | +| v4 | inherited | removed | new implementation | +| v5 | inherited | removed | new implementation inherited | + +A registration whose source version is equal to or lower than the removal boundary remains suppressed. Only a declaration with a strictly higher source version reintroduces the route. Import order must not change the result: a late-imported v1 declaration cannot resurrect a route removed from v3. + +For explicit registrations, only declared versions are candidates. A tombstone suppresses a matching explicit route at or after its boundary until a later source declaration reintroduces it. + +## Registry model + +- Keep active URLPattern objects in the existing urlpatterns list only. +- Store tombstone boundaries separately by logical endpoint and version. +- When a boundary is declared, remove already-registered patterns whose source version is equal to or lower than the boundary. +- When an older pattern is registered after a boundary, suppress it and retain an explicit removed-state record. +- When a later source version reintroduces the operation, register it normally and clear the removed state for the reintroduced concrete versions. +- Keep the original URLPattern as tombstone evidence so route-matrix output can identify the removed physical path and version. + +## Observable state and compatibility + +The state-aware version matrix must distinguish: +- active: a registered callback exists; +- removed: an explicit tombstone suppresses the route; +- missing: no route or tombstone declaration exists. + +Do not silently change the historical snapshot JSON format for consumers that do not use removal. Extend its output only when tombstones exist, with a stable marker such as REMOVED. The CLI must display removed routes explicitly and must not report them as ordinary missing gaps. + +Strict snapshots must detect an accidental deletion, an intentional removal, and an unexpected reintroduction as distinct changes. + +## Runtime and integrations + +- Removed paths are absent from urlpatterns, so Django returns 404. +- api_reverse(name, version=removed_version) raises NoReverseMatch; it never falls back. +- VersionedRouter.urls omits the tombstoned operation. +- drf-spectacular naturally excludes the route from that version's schema; the OpenAPI consumer example must test this. +- Version-wide LifecycleMiddleware continues to own Deprecation, Sunset, and 410. Endpoint tombstones do not synthesize 410. + +## Required tests + +1. Removal after registration and removal before registration produce identical results. +2. Older declarations imported after a tombstone cannot restore the route. +3. A later version reintroduces the endpoint and its URL reversal. +4. Explicit versions and internal version gaps remain correct. +5. Removing one DRF custom action preserves list/detail and unrelated actions. +6. The route matrix distinguishes active, removed, and missing states. +7. Strict snapshots detect tombstone changes. +8. api_reverse fails for the removed version and succeeds for the reintroduced version. +9. OpenAPI excludes the removed operation and includes a later reintroduction. +10. Existing decorator/router precedence and import behavior remain backward-compatible. From c36c1acb8c7d7eb480618c44481c24f0483de630 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:49 +0400 Subject: [PATCH 09/49] feat: implement explicit endpoint removal --- docs/reference/versioning-contract.md | 48 ++++++++++++++++++++++++--- 1 file changed, 43 insertions(+), 5 deletions(-) diff --git a/docs/reference/versioning-contract.md b/docs/reference/versioning-contract.md index dd91b64f..5903ab3b 100644 --- a/docs/reference/versioning-contract.md +++ b/docs/reference/versioning-contract.md @@ -27,18 +27,18 @@ Do not copy DRF examples using string identifiers such as `"v1"` or `"1.0"` into ## 2. Canonical imports and public API -The package exposes `endpoint`, `ver_range`, and `api_reverse` from its top-level namespace. The optional DRF integration is imported from `django_api_versioning.routers` so core Django users do not need DRF installed. +The package exposes `endpoint`, `remove_endpoint`, `ver_range`, and `api_reverse` from its top-level namespace. The optional DRF integration is imported from `django_api_versioning.routers` so core Django users do not need DRF installed. Use these public imports: ```python -from django_api_versioning import endpoint, ver_range, api_reverse +from django_api_versioning import endpoint, remove_endpoint, ver_range, api_reverse ``` The decorators are implemented in `django_api_versioning.decorators`, so importing them directly from that module also works: ```python -from django_api_versioning.decorators import endpoint, ver_range +from django_api_versioning.decorators import endpoint, remove_endpoint, ver_range ``` For application code and documentation examples, prefer the top-level import path. It is the package's public API and avoids coupling consumers to the internal module structure. @@ -244,6 +244,38 @@ def legacy(request): [1, 2, 3] ``` +### Explicit endpoint removal + +Forward inheritance can be stopped deliberately without deleting the route +from earlier API versions. Use the top-level remove_endpoint() function: + +```python +from django_api_versioning import endpoint, remove_endpoint + + +@endpoint("orders/", version=1, view_name="orders-list") +def orders_v1(request): + ... + + +remove_endpoint("orders/", from_version=3) +``` + +A removal boundary suppresses source declarations at or before that version +for the matching concrete route versions. A later declaration with a strictly +higher source version reintroduces the route from that version onward. The +result is independent of whether the removal or older endpoint module is +imported first. + +Removed routes are absent from Django's active URL patterns and return 404. +api_reverse() raises NoReverseMatch for a removed version; it never falls back +to an older implementation. The version-matrix snapshot records the state as +``, which is distinct from an undeclared/missing route. + +This is an endpoint-level removal, not a version retirement. It does not emit +410 or lifecycle headers; version-wide deprecation and sunset remain the +responsibility of LifecycleMiddleware. + ### Unversioned registration When neither argument is supplied, the endpoint is registered once without a version prefix: @@ -366,7 +398,13 @@ Configure `VersionedRouterVersioning` as DRF's `DEFAULT_VERSIONING_CLASS` or on A manually configured callable such as `MyViewSet.as_view({"get": "list"})` remains valid for a single route, but it does not provide the complete router-generated route set. -The router uses per-route inheritance: a later ViewSet replaces matching routes while earlier custom actions that are not redeclared remain inherited. There is not yet an explicit route-removal/tombstone API; see Issue #39. +The router uses per-route inheritance: a later ViewSet replaces matching routes while earlier custom actions that are not redeclared remain inherited. Remove one generated route/action without removing the rest of the ViewSet by using its URL name: + +```python +router.remove("orders", "order-archive", from_version=3) +``` + +The first argument is the router prefix; the second is the URL name generated from the basename and action. The removal applies from the requested version onward and can be reversed only by a later source-version registration. ## 8. Routing inheritance is not Python inheritance or contract compatibility @@ -549,7 +587,7 @@ It does not: - Select serializers based on a request version. - Replace DRF authentication, permission, throttle, filter, pagination, or renderer behavior. - Provide `DefaultRouter` API-root or format-suffix behavior; the current integration targets `SimpleRouter`. -- Remove an inherited route when a later ViewSet omits its action; explicit route tombstones are tracked separately in Issue #39. +- Infer endpoint removal from an omitted import or missing ViewSet action; use remove_endpoint() or VersionedRouter.remove() to declare it explicitly. - Enable header, query-parameter, host, or tenant-based route negotiation. `API_VERSIONING_CHANNELS` and `API_EFFECTIVE_VERSION_RESOLVER` remain reserved settings with no runtime effect. - Validate response payload compatibility through route-matrix checks. - Automatically generate versioned OpenAPI schemas or diff their compatibility; the optional drf-spectacular/oasdiff workflow is tracked in Issue #38. From 598bd879252011e2155e9cc73245633ca08865dc Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 15:59:58 +0400 Subject: [PATCH 10/49] feat: implement explicit endpoint removal --- tests/conftest.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index cee3138b..2fd904ab 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -7,8 +7,8 @@ @pytest.fixture(autouse=True) def _reset_registry(): """Clear the global registry before and after every test.""" - registry.urlpatterns.clear() + registry.clear() clear_url_caches() yield - registry.urlpatterns.clear() + registry.clear() clear_url_caches() From 265c96720a0adc6b4213166de1749139e052e3da Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:00:00 +0400 Subject: [PATCH 11/49] feat: implement explicit endpoint removal --- tests/test_registry.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_registry.py b/tests/test_registry.py index 54706999..d8dee705 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -20,11 +20,11 @@ @pytest.fixture def clear_registry(): """Clear registered routes and URL resolver caches.""" - registry.urlpatterns.clear() + registry.clear() clear_url_caches() yield - registry.urlpatterns.clear() + registry.clear() clear_url_caches() From 65fb3b56a1c11389c96640a395344f5bda8f72d6 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:00:03 +0400 Subject: [PATCH 12/49] feat: implement explicit endpoint removal --- tests/test_route_removal.py | 249 ++++++++++++++++++++++++++++++++++++ 1 file changed, 249 insertions(+) create mode 100644 tests/test_route_removal.py diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py new file mode 100644 index 00000000..57e43f93 --- /dev/null +++ b/tests/test_route_removal.py @@ -0,0 +1,249 @@ +from io import StringIO +from types import ModuleType + +import pytest +from django.core.management import call_command +from django.http import JsonResponse +from django.test import override_settings +from django.urls import NoReverseMatch, clear_url_caches + +from django_api_versioning import api_reverse, endpoint, remove_endpoint +from django_api_versioning.exceptions import VersionMatrixError +from django_api_versioning.registry import registry +from django_api_versioning.testing import assert_version_matrix, build_version_matrix + + +def _view(name): + def callback(request): + return JsonResponse({"implementation": name}) + + callback.__name__ = name + return callback + + +def _register_segment(view, source_version=1): + for version in range(source_version, 6): + registry.register( + f"api/v{version}/orders/", + view, + name="orders", + source_version=source_version, + route_version=version, + logical_endpoint="shop/orders/", + ) + + +def _register_explicit(view, versions): + for version in versions: + registry.register( + f"api/v{version}/orders/", + view, + name="orders", + source_version=version, + route_version=version, + logical_endpoint="shop/orders/", + ) + + +def _active_versions(): + return { + getattr(pattern, registry._ROUTE_VERSION_ATTR) + for pattern in registry.urlpatterns + if (getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) == "shop/orders/") + } + + +def test_remove_after_registration_suppresses_the_forward_segment(): + original = _view("orders_v1") + _register_segment(original) + + registry.remove("shop/orders/", from_version=3) + + assert _active_versions() == {1, 2} + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": ""} + assert matrix["api/v4/orders/"] == {"4": ""} + assert matrix["api/v5/orders/"] == {"5": ""} + assert api_reverse("orders", version=2) == "/api/v2/orders/" + with pytest.raises(NoReverseMatch): + api_reverse("orders", version=3) + + +def test_removal_before_registration_is_order_independent(): + original = _view("orders_v1") + registry.remove("shop/orders/", from_version=3) + _register_segment(original) + + assert _active_versions() == {1, 2} + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": ""} + assert matrix["api/v4/orders/"] == {"4": ""} + assert matrix["api/v5/orders/"] == {"5": ""} + + +def test_later_registration_reintroduces_route_without_resurrecting_gap(): + original = _view("orders_v1") + replacement = _view("orders_v4") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + _register_segment(replacement, source_version=4) + + assert _active_versions() == {1, 2, 4, 5} + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": ""} + assert matrix["api/v4/orders/"] == {"4": "orders_v4"} + assert matrix["api/v5/orders/"] == {"5": "orders_v4"} + assert api_reverse("orders", version=4) == "/api/v4/orders/" + + +def test_late_older_registration_cannot_replace_reintroduced_route(): + original = _view("orders_v1") + replacement = _view("orders_v4") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + _register_segment(replacement, source_version=4) + + # Simulate a module containing the old declaration being imported late. + for version in range(1, 6): + registry.register( + f"api/v{version}/orders/", + original, + name="orders", + source_version=1, + route_version=version, + logical_endpoint="shop/orders/", + ) + + assert _active_versions() == {1, 2, 4, 5} + assert { + getattr(pattern, registry._ROUTE_VERSION_ATTR): pattern.callback + for pattern in registry.urlpatterns + if getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) == "shop/orders/" + }[4] is replacement + + +def test_explicit_version_registration_respects_removal_boundary(): + original = _view("orders_explicit") + _register_explicit(original, [1, 3, 5]) + registry.remove("shop/orders/", from_version=3) + + assert _active_versions() == {1, 5} + assert api_reverse("orders", version=5) == "/api/v5/orders/" + with pytest.raises(NoReverseMatch): + api_reverse("orders", version=3) + + +def test_public_remove_endpoint_uses_decorator_logical_identity(): + @endpoint("invoices/", version=1, view_name="invoices", app_name="billing") + def invoices(request): + return JsonResponse({}) + + remove_endpoint("invoices/", from_version=4, app_name="billing") + + assert { + getattr(pattern, registry._ROUTE_VERSION_ATTR) + for pattern in registry.urlpatterns + if ( + getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) + == "billing/invoices/" + ) + } == {1, 2, 3} + with pytest.raises(NoReverseMatch): + api_reverse("invoices", version=4) + + +def test_router_removal_is_action_specific(): + from django_api_versioning.routers import VersionedRouter + from rest_framework import viewsets + from rest_framework.decorators import action + from rest_framework.response import Response + from rest_framework.test import APIClient + + class OrderViewSetV1(viewsets.ViewSet): + def list(self, request): + return Response({}) + + @action(detail=False, methods=["get"], url_path="archive") + def archive(self, request): + return Response({}) + + router = VersionedRouter() + router.register("orders", OrderViewSetV1, version=1, basename="order") + router.remove("orders", "order-archive", from_version=3) + + active = { + pattern.name + for pattern in registry.urlpatterns + if getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, "").startswith("orders:") + } + assert "order-list" in active + assert "order-archive" in active + urlconf = ModuleType("route_removal_test_urls") + urlconf.urlpatterns = router.urls + clear_url_caches() + + with override_settings(ROOT_URLCONF=urlconf): + client = APIClient() + assert client.get("/api/v2/orders/archive/").status_code == 200 + assert client.get("/api/v3/orders/").status_code == 200 + assert client.get("/api/v3/orders/archive/").status_code == 404 + + assert all( + getattr(pattern, registry._ROUTE_VERSION_ATTR) < 3 + for pattern in registry.urlpatterns + if ( + getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, None) + == "orders:order-archive" + ) + ) + + +def test_strict_snapshot_distinguishes_removed_from_missing(tmp_path): + original = _view("orders_v1") + _register_segment(original) + snapshot = tmp_path / "version-matrix.json" + + assert_version_matrix(snapshot=str(snapshot), update=True, strict=True) + registry.remove("shop/orders/", from_version=3) + + with pytest.raises(VersionMatrixError, match=""): + assert_version_matrix(snapshot=str(snapshot), strict=True) + + assert_version_matrix(snapshot=str(snapshot), update=True, strict=True) + import json + + expected = json.loads(snapshot.read_text()) + assert expected["api/v3/orders/"] == {"3": ""} + assert_version_matrix(snapshot=str(snapshot), strict=True) + + +def test_reused_physical_path_keeps_the_new_active_route_in_snapshot(): + original = _view("orders_v1") + replacement = _view("orders_v3_replacement") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + + registry.register( + "api/v3/orders/", + replacement, + name="orders", + source_version=3, + route_version=3, + logical_endpoint="shop/replacement-orders/", + ) + + matrix = build_version_matrix() + assert matrix["api/v3/orders/"] == {"3": "orders_v3_replacement"} + + +def test_check_versions_displays_explicit_removed_state(): + original = _view("orders_v1") + _register_segment(original) + registry.remove("shop/orders/", from_version=3) + + output = StringIO() + call_command("check_versions", stdout=output) + + assert "shop/orders/" in output.getvalue() + assert "v3" in output.getvalue() + assert "" in output.getvalue() From b9cc31200f7262b8f84b90a6a683619decd61570 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:01:02 +0400 Subject: [PATCH 13/49] fix: preserve lazy DRF router import with route removal --- django_api_versioning/routers.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/django_api_versioning/routers.py b/django_api_versioning/routers.py index 75c1f257..b8956bc3 100644 --- a/django_api_versioning/routers.py +++ b/django_api_versioning/routers.py @@ -11,8 +11,7 @@ try: from rest_framework.exceptions import NotFound - from rest_framework.routers import SimpleRouter - from rest_framework.versioning import BaseVersioning + from rest_framework.versioning import NamespaceVersioning except ImportError as exc: # pragma: no cover - exercised without optional DRF raise ImportError( "VersionedRouter requires Django REST Framework. Install a DRF release " @@ -160,6 +159,11 @@ def _register_version( source_version: int | None, route_version: int | None, ) -> None: + # Import lazily: DRF's SimpleRouter imports APIView, which resolves + # DEFAULT_VERSIONING_CLASS. Importing it at module load time would + # recurse while DRF is trying to import VersionedRouterVersioning. + from rest_framework.routers import SimpleRouter + route_prefix = prefix if route_version is not None: route_prefix = ( @@ -235,7 +239,7 @@ def urls(self) -> list[URLPattern | URLResolver]: return urlpatterns -class VersionedRouterVersioning(BaseVersioning): +class VersionedRouterVersioning(NamespaceVersioning): """Expose the router-selected version through DRF's request.version. The router namespaces each concrete version as vN. This adapter reads @@ -293,8 +297,8 @@ def reverse( format: str | None = None, **extra: Any, ) -> str: - if request is not None: - viewname = self.get_versioned_viewname(viewname, request) + # NamespaceVersioning.reverse() calls our get_versioned_viewname(). + # Do not pre-qualify the name here or the namespace would be applied twice. return super().reverse( viewname, args=args, From 7189f4a654864400f02be398a378c175a9187391 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:03:39 +0400 Subject: [PATCH 14/49] docs: mark 1.1.0 as the current stable release --- docs/reference/versioning-contract.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/reference/versioning-contract.md b/docs/reference/versioning-contract.md index 5903ab3b..a0655667 100644 --- a/docs/reference/versioning-contract.md +++ b/docs/reference/versioning-contract.md @@ -1,8 +1,8 @@ # django-api-versioning: canonical routing contract -> **Applies to:** the `1.1.0` release candidate on `main`; the `v1.1.0` tag is created only after the release PR is merged and verified. -> **Current stable release:** `1.0.1`, published from the annotated `v1.0.1` tag. The tag-based publish workflow verifies the tag target, runs the compatibility matrix, builds and verifies the wheel and sdist, smoke-tests the installed wheel, and publishes the verified artifacts to PyPI through Trusted Publishing. The configured Python/Django environments are defined in [`tox.ini`](../../tox.ini) and checked against the [compatibility workflow](../../.github/workflows/compatibility.yml). Actual outcomes are commit-specific; consult the [workflow run history](https://github.com/mojtaba-arvin/django-api-versioning/actions/workflows/compatibility.yml) rather than treating the configured matrix as proof of a passing run. The [v0.3.8 compatibility report](../reports/compatibility-0.3.8.md) is historical evidence for that release only. +> **Applies to:** `django-api-versioning` `1.1.0`, published from the annotated `v1.1.0` tag. +> **Current stable release:** `1.1.0`. The tag-based publish workflow verified the release tag, ran the compatibility matrix, built and verified the wheel and sdist, smoke-tested the installed wheel, and published both artifacts to PyPI through Trusted Publishing. The release workflow completed successfully on commit `66bb4da557b9df4081be3ee65b9ad01db5030f2a`. The tag-based publish workflow verifies the tag target, runs the compatibility matrix, builds and verifies the wheel and sdist, smoke-tests the installed wheel, and publishes the verified artifacts to PyPI through Trusted Publishing. The configured Python/Django environments are defined in [`tox.ini`](../../tox.ini) and checked against the [compatibility workflow](../../.github/workflows/compatibility.yml). Actual outcomes are commit-specific; consult the [workflow run history](https://github.com/mojtaba-arvin/django-api-versioning/actions/workflows/compatibility.yml) rather than treating the configured matrix as proof of a passing run. The [v0.3.8 compatibility report](../reports/compatibility-0.3.8.md) is historical evidence for that release only. > > This document defines the package-specific contract for version identifiers, public imports, URL construction, endpoint registration, route precedence, URL reversal, and Django REST Framework integration. > From fd94c3460d9a8b368779c16f9be434486d90d95e Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:04:01 +0400 Subject: [PATCH 15/49] style: satisfy Black for endpoint tombstone registry --- django_api_versioning/registry.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/django_api_versioning/registry.py b/django_api_versioning/registry.py index 78b761f3..382a2d20 100644 --- a/django_api_versioning/registry.py +++ b/django_api_versioning/registry.py @@ -173,7 +173,9 @@ def register_urlpattern( existing_logical = getattr(existing, self._LOGICAL_ENDPOINT_ATTR, None) existing_version = getattr(existing, self._ROUTE_VERSION_ATTR, None) existing_source = getattr(existing, self._SOURCE_VERSION_ATTR, None) - if self._is_suppressed(existing_logical, existing_version, existing_source): + if self._is_suppressed( + existing_logical, existing_version, existing_source + ): del self.urlpatterns[route_index] if logical_endpoint is not None: self._record_removed(pattern, logical_endpoint) From 098371f5b0519f0d4307935204d07db79336f5aa Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:30:25 +0400 Subject: [PATCH 16/49] style: fix import grouping in endpoint removal tests --- tests/test_route_removal.py | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py index 57e43f93..7e80cdce 100644 --- a/tests/test_route_removal.py +++ b/tests/test_route_removal.py @@ -154,6 +154,7 @@ def invoices(request): def test_router_removal_is_action_specific(): from django_api_versioning.routers import VersionedRouter + from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response From d7f1a64378577de9ebb5bf8af4bda7a908cbcdea Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:31:13 +0400 Subject: [PATCH 17/49] test(openapi): remove a versioned action from v2 --- examples/openapi_contract/contract_project/urls.py | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/openapi_contract/contract_project/urls.py b/examples/openapi_contract/contract_project/urls.py index a36c0605..9555b760 100644 --- a/examples/openapi_contract/contract_project/urls.py +++ b/examples/openapi_contract/contract_project/urls.py @@ -7,4 +7,5 @@ router = VersionedRouter() router.register("products", ProductViewSetV1, version=1, basename="product") router.register("products", ProductViewSetV2, version=2, basename="product") +router.remove("products", "product-legacy-export", from_version=2) urlpatterns = router.urls From 0d54817a6cb76f4c9ec34c58ca0c4a14bbe68ffb Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:31:16 +0400 Subject: [PATCH 18/49] test(openapi): add a removable legacy action fixture --- examples/openapi_contract/contract_app/views.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/examples/openapi_contract/contract_app/views.py b/examples/openapi_contract/contract_app/views.py index 08623a2e..8a6528b7 100644 --- a/examples/openapi_contract/contract_app/views.py +++ b/examples/openapi_contract/contract_app/views.py @@ -32,6 +32,15 @@ def retrieve(self, request, pk: int | None = None): payload = {"id": int(pk or 1), "name": "Desk lamp", "price": "12.50"} return Response(self.get_serializer(payload).data) + @extend_schema(responses=AvailabilitySerializer) + @action(detail=False, methods=["get"], url_path="legacy-export") + def legacy_export(self, request): + payload = { + "available": True, + "checked_at": datetime(2026, 1, 1, tzinfo=timezone.utc), + } + return Response(AvailabilitySerializer(payload).data) + @extend_schema(responses=AvailabilitySerializer) @action(detail=False, methods=["get"]) def availability(self, request): From d68a183d02f182d789070482221db011b199c6ae Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:31:18 +0400 Subject: [PATCH 19/49] test(openapi): assert removed actions stay out of v2 schema --- examples/openapi_contract/verify.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/examples/openapi_contract/verify.py b/examples/openapi_contract/verify.py index b0ec54ab..710df673 100644 --- a/examples/openapi_contract/verify.py +++ b/examples/openapi_contract/verify.py @@ -18,6 +18,10 @@ "1": "/api/v1/products/availability/", "2": "/api/v2/products/availability/", } +LEGACY_EXPORT_PATHS = { + "1": "/api/v1/products/legacy-export/", + "2": "/api/v2/products/legacy-export/", +} def generate(version: str, output: Path) -> bytes: @@ -76,6 +80,11 @@ def verify_runtime() -> None: inherited = client.get("/api/v2/products/availability/") assert inherited.status_code == 200, inherited.content assert inherited.json()["available"] is True + +legacy_v1 = client.get("/api/v1/products/legacy-export/") +assert legacy_v1.status_code == 200, legacy_v1.content +legacy_v2 = client.get("/api/v2/products/legacy-export/") +assert legacy_v2.status_code == 404, legacy_v2.content """ subprocess.run([sys.executable, "-c", code], cwd=ROOT, env=env, check=True) @@ -102,6 +111,8 @@ def verify_schema(version: str) -> dict: assert product_path in document["paths"] assert action_path in document["paths"] assert PRODUCT_PATHS[other_version] not in document["paths"] + legacy_path = LEGACY_EXPORT_PATHS[version] + assert (legacy_path in document["paths"]) is (version == "1") product = component(document, response_schema(document, product_path)) fields = product["properties"] @@ -130,6 +141,7 @@ def main() -> None: "deterministic": True, "version_specific_serializers": True, "inherited_custom_action": True, + "removed_action_absent_from_v2_runtime_and_schema": True, }, indent=2, ) From 31a5f323207ee9ea52b1849335bca627a9e537b6 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:31:47 +0400 Subject: [PATCH 20/49] style: align optional DRF test imports with isort sections --- tests/test_route_removal.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py index 7e80cdce..32fabe90 100644 --- a/tests/test_route_removal.py +++ b/tests/test_route_removal.py @@ -153,13 +153,13 @@ def invoices(request): def test_router_removal_is_action_specific(): - from django_api_versioning.routers import VersionedRouter - from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.test import APIClient + from django_api_versioning.routers import VersionedRouter + class OrderViewSetV1(viewsets.ViewSet): def list(self, request): return Response({}) From d8f6d5c38535e4c473de486fce94e921662cdfca Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:32:02 +0400 Subject: [PATCH 21/49] test(openapi): avoid collision with detail route in removal fixture --- examples/openapi_contract/contract_app/views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/openapi_contract/contract_app/views.py b/examples/openapi_contract/contract_app/views.py index 8a6528b7..3d1e612a 100644 --- a/examples/openapi_contract/contract_app/views.py +++ b/examples/openapi_contract/contract_app/views.py @@ -33,7 +33,7 @@ def retrieve(self, request, pk: int | None = None): return Response(self.get_serializer(payload).data) @extend_schema(responses=AvailabilitySerializer) - @action(detail=False, methods=["get"], url_path="legacy-export") + @action(detail=False, methods=["get"], url_path="legacy/export") def legacy_export(self, request): payload = { "available": True, From 8014fa0eb8d13ce1f95d6254c97f422027b67605 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:32:05 +0400 Subject: [PATCH 22/49] test(openapi): verify nested legacy action removal path --- examples/openapi_contract/verify.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/openapi_contract/verify.py b/examples/openapi_contract/verify.py index 710df673..41791406 100644 --- a/examples/openapi_contract/verify.py +++ b/examples/openapi_contract/verify.py @@ -19,8 +19,8 @@ "2": "/api/v2/products/availability/", } LEGACY_EXPORT_PATHS = { - "1": "/api/v1/products/legacy-export/", - "2": "/api/v2/products/legacy-export/", + "1": "/api/v1/products/legacy/export/", + "2": "/api/v2/products/legacy/export/", } @@ -81,9 +81,9 @@ def verify_runtime() -> None: assert inherited.status_code == 200, inherited.content assert inherited.json()["available"] is True -legacy_v1 = client.get("/api/v1/products/legacy-export/") +legacy_v1 = client.get("/api/v1/products/legacy/export/") assert legacy_v1.status_code == 200, legacy_v1.content -legacy_v2 = client.get("/api/v2/products/legacy-export/") +legacy_v2 = client.get("/api/v2/products/legacy/export/") assert legacy_v2.status_code == 404, legacy_v2.content """ subprocess.run([sys.executable, "-c", code], cwd=ROOT, env=env, check=True) From 34ae69dd386b43c1af1c0d8414ef418cc5422cd0 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:33:08 +0400 Subject: [PATCH 23/49] ci(openapi): publish candidate schemas before contract verification --- .github/workflows/openapi-contract.yml | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/openapi-contract.yml b/.github/workflows/openapi-contract.yml index c6fe66e6..029d6dd2 100644 --- a/.github/workflows/openapi-contract.yml +++ b/.github/workflows/openapi-contract.yml @@ -33,14 +33,23 @@ jobs: python -m pip install -e . python -m pip install -r examples/openapi_contract/requirements.txt - - name: Verify runtime routing and versioned OpenAPI schemas - run: python examples/openapi_contract/verify.py - - name: Export versioned OpenAPI schemas run: | python examples/openapi_contract/generate_schemas.py \ --output-dir "$RUNNER_TEMP/openapi-contract-schemas" + - name: Upload generated OpenAPI schemas for review + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: versioned-openapi-contract-schemas + path: ${{ runner.temp }}/openapi-contract-schemas/ + if-no-files-found: ignore + retention-days: 7 + + + - name: Verify runtime routing and versioned OpenAPI schemas + run: python examples/openapi_contract/verify.py + - name: Install pinned oasdiff run: | archive="$RUNNER_TEMP/oasdiff_1.38.0_linux_amd64.tar.gz" From 1ae04704fa211919e7b3706537259974cc730da6 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:33:17 +0400 Subject: [PATCH 24/49] ci(openapi): keep a single pre-verification schema artifact upload --- .github/workflows/openapi-contract.yml | 8 -------- 1 file changed, 8 deletions(-) diff --git a/.github/workflows/openapi-contract.yml b/.github/workflows/openapi-contract.yml index 029d6dd2..4842caf5 100644 --- a/.github/workflows/openapi-contract.yml +++ b/.github/workflows/openapi-contract.yml @@ -46,7 +46,6 @@ jobs: if-no-files-found: ignore retention-days: 7 - - name: Verify runtime routing and versioned OpenAPI schemas run: python examples/openapi_contract/verify.py @@ -79,10 +78,3 @@ jobs: examples/openapi_contract/schemas/v2/openapi.yaml \ "$RUNNER_TEMP/openapi-contract-schemas/v2/openapi.yaml" - - name: Upload generated OpenAPI schemas for review - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 - with: - name: versioned-openapi-contract-schemas - path: ${{ runner.temp }}/openapi-contract-schemas/ - if-no-files-found: error - retention-days: 7 From 4dd42d0fcb5ac50606d18515d834a6aef3f8d231 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:34:07 +0400 Subject: [PATCH 25/49] ci(lint): print actionable isort diffs on failure --- tox.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tox.ini b/tox.ini index 10a0fe2a..ca07e6e0 100644 --- a/tox.ini +++ b/tox.ini @@ -17,7 +17,7 @@ deps = commands = flake8 django_api_versioning tests integration_test_project scripts black --check . - isort --check-only . + isort --check-only --diff . [testenv] setenv = From 617c343158fb72affaadf8c8f2857b56e4644ae5 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:34:35 +0400 Subject: [PATCH 26/49] test(openapi): baseline v1 legacy action before v2 removal --- examples/openapi_contract/schemas/v1/openapi.yaml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/examples/openapi_contract/schemas/v1/openapi.yaml b/examples/openapi_contract/schemas/v1/openapi.yaml index 64ccec91..edb4d475 100644 --- a/examples/openapi_contract/schemas/v1/openapi.yaml +++ b/examples/openapi_contract/schemas/v1/openapi.yaml @@ -51,6 +51,19 @@ paths: schema: $ref: '#/components/schemas/Availability' description: '' + /api/v1/products/legacy/export/: + get: + operationId: v1_products_legacy_export_retrieve + description: V1 implementation and custom action inherited by V2. + tags: + - v1 + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/Availability' + description: '' components: schemas: Availability: From 35142b817591db6dbb9c1a27c379b6571c401d16 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:35:34 +0400 Subject: [PATCH 27/49] docs(openapi): explain the version-specific removal example --- examples/openapi_contract/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/openapi_contract/README.md b/examples/openapi_contract/README.md index 60cc099c..875e81d9 100644 --- a/examples/openapi_contract/README.md +++ b/examples/openapi_contract/README.md @@ -3,6 +3,8 @@ This executable consumer project uses the public VersionedRouter API and the same URLconf for runtime requests and drf-spectacular schema generation. +The V1-only `legacy/export/` action is explicitly removed from V2. The verifier checks that it remains available and present in the V1 schema, while returning 404 and disappearing from the V2 schema. + It deliberately tests: - V1 and V2 implementations for the same list/detail routes. - Different serializer contracts for the two versions. From f7327424e99c005de01bc1a75aced77e446ec090 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:38:01 +0400 Subject: [PATCH 28/49] docs(changelog): record explicit endpoint removal --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17e32e8d..1056f0fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Add explicit endpoint removal through `remove_endpoint()` and `VersionedRouter.remove()`. Removed routes remain available in earlier API versions, disappear from runtime routing and URL reversal at the removal boundary, and may be explicitly reintroduced by a later version declaration. + ## [1.1.0] - 2026-11-18 ### Added From 59305ad2dc41f32671111cb5d34c95d9f73b1aaf Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:38:39 +0400 Subject: [PATCH 29/49] ci(matrix): use a bounded compatibility smoke matrix on pull requests --- .github/workflows/compatibility.yml | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index 3befd2c9..b045c27b 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -2,7 +2,7 @@ name: Compatibility matrix on: # Standard GitHub-hosted runners are free for public repositories. - # Run the complete compatibility matrix for package/test changes and on PR review. + # Run the complete matrix on main and for releases; PRs use a bounded smoke matrix. push: branches: - main @@ -18,7 +18,22 @@ on: - ".github/workflows/compatibility.yml" - ".github/workflows/publish.yml" workflow_dispatch: + inputs: + scope: + description: "Select the full matrix or the bounded pull-request smoke matrix." + required: false + type: choice + options: + - full + - pull-request + default: full workflow_call: + inputs: + scope: + description: "Full matrix by default; pull-request selects boundary environments only." + required: false + type: string + default: full permissions: contents: read @@ -88,6 +103,9 @@ jobs: needs: validate-matrix name: ${{ matrix.env }} runs-on: ubuntu-latest + if: >- + inputs.scope != 'pull-request' || + contains(fromJSON('["py310-django42","py315-django61","lint"]'), matrix.env) timeout-minutes: 30 strategy: fail-fast: false From f346f178bc06eed4a5375c4c8fb5ba906506eb24 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:38:41 +0400 Subject: [PATCH 30/49] ci(gate): select bounded compatibility checks for pull requests --- .github/workflows/pull-request-gate.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/pull-request-gate.yml b/.github/workflows/pull-request-gate.yml index 5393078f..891cbb08 100644 --- a/.github/workflows/pull-request-gate.yml +++ b/.github/workflows/pull-request-gate.yml @@ -60,6 +60,8 @@ jobs: needs: changes if: needs.changes.outputs.compatibility == 'true' uses: ./.github/workflows/compatibility.yml + with: + scope: pull-request permissions: contents: read From 5b914996772978f98fee429cc0ebdc3d37f1e2a1 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:39:13 +0400 Subject: [PATCH 31/49] ci(matrix): split PR smoke checks from the full compatibility matrix --- .github/workflows/compatibility.yml | 46 +++++++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 3 deletions(-) diff --git a/.github/workflows/compatibility.yml b/.github/workflows/compatibility.yml index b045c27b..a61c87f2 100644 --- a/.github/workflows/compatibility.yml +++ b/.github/workflows/compatibility.yml @@ -103,9 +103,7 @@ jobs: needs: validate-matrix name: ${{ matrix.env }} runs-on: ubuntu-latest - if: >- - inputs.scope != 'pull-request' || - contains(fromJSON('["py310-django42","py315-django61","lint"]'), matrix.env) + if: inputs.scope != 'pull-request' timeout-minutes: 30 strategy: fail-fast: false @@ -168,3 +166,45 @@ jobs: - name: Run compatibility environment run: tox run -e ${{ matrix.env }} + + tox-pr-smoke: + needs: validate-matrix + name: PR smoke / ${{ matrix.env }} + if: inputs.scope == 'pull-request' + runs-on: ubuntu-latest + timeout-minutes: 30 + strategy: + fail-fast: false + matrix: + include: + - env: py310-django42 + python: "3.10" + - env: py315-django61 + python: "3.15" + - env: lint + python: "3.15" + + steps: + - name: Checkout source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + with: + python-version: ${{ matrix.python }} + + - name: Cache uv environments + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6 + with: + path: ~/.cache/uv + key: uv-${{ runner.os }}-${{ matrix.env }}-${{ hashFiles('tox.ini', 'pyproject.toml') }} + restore-keys: | + uv-${{ runner.os }}-${{ matrix.env }}- + + - name: Install tox and tox-uv + run: python -m pip install tox tox-uv + + - name: Run compatibility smoke environment + run: tox run -e ${{ matrix.env }} From 2b8a5013ed33d9b78df33e76457446f5e40d8c40 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:41:15 +0400 Subject: [PATCH 32/49] ci(matrix): validate full and PR smoke matrices independently --- scripts/check_tox_workflow_matrix.py | 53 +++++++++++++++++++++------- 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/scripts/check_tox_workflow_matrix.py b/scripts/check_tox_workflow_matrix.py index 8ed8d4d6..7ec21f28 100644 --- a/scripts/check_tox_workflow_matrix.py +++ b/scripts/check_tox_workflow_matrix.py @@ -14,6 +14,22 @@ WORKFLOW = ROOT / ".github" / "workflows" / "compatibility.yml" +def matrix_entries_for_job(workflow_text: str, job_id: str) -> list[str]: + """Return environment names from one job's matrix include list.""" + match = re.search( + rf"(?ms)^ {re.escape(job_id)}:\n(.*?)(?=^ [A-Za-z0-9_-]+:\n|\Z)", + workflow_text, + ) + if match is None: + raise ValueError(f"Could not find the {job_id!r} job in compatibility.yml.") + + return re.findall( + r"^\s+- env:\s*([A-Za-z0-9_.-]+)\s*$", + match.group(1), + flags=re.MULTILINE, + ) + + def main() -> int: tox_executable = shutil.which("tox") command = ( @@ -43,25 +59,35 @@ def main() -> int: return 2 workflow_text = WORKFLOW.read_text(encoding="utf-8") - matrix_entries = re.findall( - r"^\s+- env:\s*([A-Za-z0-9_.-]+)\s*$", - workflow_text, - flags=re.MULTILINE, - ) - workflow_environments = set(matrix_entries) + try: + full_entries = matrix_entries_for_job(workflow_text, "tox") + smoke_entries = matrix_entries_for_job(workflow_text, "tox-pr-smoke") + except ValueError as exc: + print(str(exc), file=sys.stderr) + return 2 - if len(matrix_entries) != len(workflow_environments): + full_environments = set(full_entries) + smoke_environments = set(smoke_entries) + if len(full_entries) != len(full_environments): + print("Duplicate environment names found in the full tox matrix.", file=sys.stderr) + return 1 + if len(smoke_entries) != len(smoke_environments): + print("Duplicate environment names found in the PR smoke matrix.", file=sys.stderr) + return 1 + + smoke_only = sorted(smoke_environments - full_environments) + if smoke_only: print( - "Duplicate environment names found in compatibility.yml.", + f"PR smoke environments are absent from the full matrix: {', '.join(smoke_only)}", file=sys.stderr, ) return 1 - missing_from_workflow = sorted(tox_environments - workflow_environments) - missing_from_tox = sorted(workflow_environments - tox_environments) + missing_from_workflow = sorted(tox_environments - full_environments) + missing_from_tox = sorted(full_environments - tox_environments) if missing_from_workflow or missing_from_tox: print( - "tox.ini and compatibility.yml define different environments.", + "tox.ini and the full compatibility matrix define different environments.", file=sys.stderr, ) if missing_from_workflow: @@ -76,7 +102,10 @@ def main() -> int: ) return 1 - print(f"Verified {len(tox_environments)} tox environments.") + print( + f"Verified {len(tox_environments)} full tox environments and " + f"{len(smoke_environments)} PR smoke environments." + ) return 0 From 96012268a38289914d03c2ae611d49b157b950e4 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:44:00 +0400 Subject: [PATCH 33/49] style(matrix): format matrix validation diagnostics --- scripts/check_tox_workflow_matrix.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/scripts/check_tox_workflow_matrix.py b/scripts/check_tox_workflow_matrix.py index 7ec21f28..6172ddeb 100644 --- a/scripts/check_tox_workflow_matrix.py +++ b/scripts/check_tox_workflow_matrix.py @@ -35,7 +35,16 @@ def main() -> int: command = ( [tox_executable, "config", "-k", "type", "--format", "json"] if tox_executable - else [sys.executable, "-m", "tox", "config", "-k", "type", "--format", "json"] + else [ + sys.executable, + "-m", + "tox", + "config", + "-k", + "type", + "--format", + "json", + ] ) result = subprocess.run( command, @@ -69,16 +78,23 @@ def main() -> int: full_environments = set(full_entries) smoke_environments = set(smoke_entries) if len(full_entries) != len(full_environments): - print("Duplicate environment names found in the full tox matrix.", file=sys.stderr) + print( + "Duplicate environment names found in the full tox matrix.", + file=sys.stderr, + ) return 1 if len(smoke_entries) != len(smoke_environments): - print("Duplicate environment names found in the PR smoke matrix.", file=sys.stderr) + print( + "Duplicate environment names found in the PR smoke matrix.", + file=sys.stderr, + ) return 1 smoke_only = sorted(smoke_environments - full_environments) if smoke_only: print( - f"PR smoke environments are absent from the full matrix: {', '.join(smoke_only)}", + "PR smoke environments are absent from the full matrix: " + f"{', '.join(smoke_only)}", file=sys.stderr, ) return 1 From fb710683a87ff4b091735de05cbe4a79133a659d Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:46:45 +0400 Subject: [PATCH 34/49] test(lifecycle): configure a deprecated v1 contract example --- examples/openapi_contract/contract_project/settings.py | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/examples/openapi_contract/contract_project/settings.py b/examples/openapi_contract/contract_project/settings.py index 43f44c50..829beef6 100644 --- a/examples/openapi_contract/contract_project/settings.py +++ b/examples/openapi_contract/contract_project/settings.py @@ -19,7 +19,7 @@ "django_api_versioning", "contract_app", ] -MIDDLEWARE = [] +MIDDLEWARE = ["django_api_versioning.lifecycle.LifecycleMiddleware"] DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}} DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" USE_TZ = True @@ -30,6 +30,14 @@ API_BASE_PATH = "api/v{version}/" API_MIN_VERSION = 1 API_MAX_VERSION = 2 +API_VERSION_LIFECYCLE = { + 1: { + "status": "deprecated", + "deprecated_at": "2026-01-01T00:00:00+00:00", + "sunset": "2027-06-30", + }, + 2: {"status": "active"}, +} REST_FRAMEWORK = { "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema", From ce0d37fc8b1711a9e02fd1e622f9091dbd42d55c Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:46:49 +0400 Subject: [PATCH 35/49] test(lifecycle): assert deprecation and sunset response headers --- examples/openapi_contract/verify.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/openapi_contract/verify.py b/examples/openapi_contract/verify.py index 41791406..fedb8598 100644 --- a/examples/openapi_contract/verify.py +++ b/examples/openapi_contract/verify.py @@ -72,10 +72,14 @@ def verify_runtime() -> None: assert v1.status_code == 200, v1.content assert v1.json()[0]["price"] == "12.50" assert "currency" not in v1.json()[0] +assert v1.headers["Deprecation"] == "@1767225600" +assert v1.headers["Sunset"] == "Wed, 30 Jun 2027 00:00:00 GMT" v2 = client.get("/api/v2/products/") assert v2.status_code == 200, v2.content assert v2.json()[0]["currency"] == "USD" +assert "Deprecation" not in v2.headers +assert "Sunset" not in v2.headers inherited = client.get("/api/v2/products/availability/") assert inherited.status_code == 200, inherited.content From 7bf6838118d29fbaa1e5df157b5ffb2714693866 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 16:46:52 +0400 Subject: [PATCH 36/49] docs(openapi): distinguish endpoint removal from version retirement --- examples/openapi_contract/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/openapi_contract/README.md b/examples/openapi_contract/README.md index 875e81d9..2d629510 100644 --- a/examples/openapi_contract/README.md +++ b/examples/openapi_contract/README.md @@ -5,6 +5,8 @@ same URLconf for runtime requests and drf-spectacular schema generation. The V1-only `legacy/export/` action is explicitly removed from V2. The verifier checks that it remains available and present in the V1 schema, while returning 404 and disappearing from the V2 schema. +Version lifecycle is separate from route removal: V1 is marked deprecated and emits RFC 9745 `Deprecation` plus RFC 8594 `Sunset` headers, while V2 remains active. To roll back the V2 endpoint removal before release, revert the `router.remove()` declaration; the V1 registration remains unchanged. + It deliberately tests: - V1 and V2 implementations for the same list/detail routes. - Different serializer contracts for the two versions. From bdef1920f145272537a820395a1d60b7395b9b57 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:34:37 +0400 Subject: [PATCH 37/49] docs(design): mark endpoint removal contract implemented --- docs/design/endpoint-removal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/endpoint-removal.md b/docs/design/endpoint-removal.md index 5c890e89..5a73e9a5 100644 --- a/docs/design/endpoint-removal.md +++ b/docs/design/endpoint-removal.md @@ -1,6 +1,6 @@ # Explicit endpoint removal and reintroduction -**Status:** Implementation in progress +**Status:** Implemented in PR #44 **Runtime policy:** Removed endpoint routes are absent and resolve to 404 **Scope:** Django-native endpoints and DRF VersionedRouter routes From 9694a9d19269b962c5618da000535de03f231aae Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:34:40 +0400 Subject: [PATCH 38/49] docs(readme): retain the executable OpenAPI contract example link --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 13146eb5..bd823376 100644 --- a/README.md +++ b/README.md @@ -181,6 +181,8 @@ pip install "djangorestframework>=3.18.3,<3.19" See the [Versioned DRF ViewSet guide](https://mojtaba-arvin.github.io/django-api-versioning/articles/025-django-api-versioning-viewset-support-limitations/) for route inheritance, reversal, namespaces, and the exact integration boundary. +For an optional, executable OpenAPI workflow, see the [versioned OpenAPI contract example](https://github.com/mojtaba-arvin/django-api-versioning/tree/main/examples/openapi_contract). It demonstrates per-version drf-spectacular generation and serializer introspection; it does not make drf-spectacular or oasdiff runtime dependencies. + ## Requirements - Python 3.10+ From d88ba26ba30a4839e17e867a4ced7c45cea81c2a Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:34:43 +0400 Subject: [PATCH 39/49] ci(openapi): fail if generated schema artifacts are missing --- .github/workflows/openapi-contract.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/openapi-contract.yml b/.github/workflows/openapi-contract.yml index 4842caf5..c1ad4f37 100644 --- a/.github/workflows/openapi-contract.yml +++ b/.github/workflows/openapi-contract.yml @@ -43,7 +43,7 @@ jobs: with: name: versioned-openapi-contract-schemas path: ${{ runner.temp }}/openapi-contract-schemas/ - if-no-files-found: ignore + if-no-files-found: error retention-days: 7 - name: Verify runtime routing and versioned OpenAPI schemas From 3b8877627d2cbd766ecbbd03cc8bbca3da526204 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:44:57 +0400 Subject: [PATCH 40/49] fix: validate endpoint removal router prefixes --- django_api_versioning/routers.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/django_api_versioning/routers.py b/django_api_versioning/routers.py index b8956bc3..b40026b6 100644 --- a/django_api_versioning/routers.py +++ b/django_api_versioning/routers.py @@ -135,9 +135,16 @@ def remove(self, prefix: str, route_name: str, *, from_version: int) -> None: route_name is the URL name generated from the registration basename and action (for example, "order-archive"), not a regex pattern. """ - if not isinstance(prefix, str) or not prefix: - raise VersioningError("prefix must be a non-empty string.") - if not isinstance(route_name, str) or not route_name: + if not isinstance(prefix, str): + raise TypeError("prefix must be a string.") + if not prefix or prefix.startswith("/") or prefix.endswith("/"): + raise VersioningError( + "prefix must be a non-empty relative path without leading " + "or trailing '/'." + ) + if not isinstance(route_name, str): + raise TypeError("route_name must be a string.") + if not route_name: raise VersioningError("route_name must be a non-empty string.") registry.remove(f"{prefix}:{route_name}", from_version) From d25e706b8e79eb0e694232208bee845bfa576fe2 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:45:00 +0400 Subject: [PATCH 41/49] test: cover invalid router removal declarations --- tests/test_route_removal.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py index 32fabe90..30ac8c39 100644 --- a/tests/test_route_removal.py +++ b/tests/test_route_removal.py @@ -8,7 +8,7 @@ from django.urls import NoReverseMatch, clear_url_caches from django_api_versioning import api_reverse, endpoint, remove_endpoint -from django_api_versioning.exceptions import VersionMatrixError +from django_api_versioning.exceptions import VersionMatrixError, VersioningError from django_api_versioning.registry import registry from django_api_versioning.testing import assert_version_matrix, build_version_matrix @@ -248,3 +248,21 @@ def test_check_versions_displays_explicit_removed_state(): assert "shop/orders/" in output.getvalue() assert "v3" in output.getvalue() assert "" in output.getvalue() + + + +@pytest.mark.parametrize("prefix", ["/orders", "orders/"]) +def test_router_remove_rejects_non_normalized_prefix(prefix): + from django_api_versioning.routers import VersionedRouter + + router = VersionedRouter() + with pytest.raises(VersioningError, match="relative path"): + router.remove(prefix, "order-archive", from_version=3) + + +def test_router_remove_rejects_empty_route_name(): + from django_api_versioning.routers import VersionedRouter + + router = VersionedRouter() + with pytest.raises(VersioningError, match="route_name"): + router.remove("orders", "", from_version=3) From 3815c20252c23776ca8f5422166dfdd26bf29d21 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:45:02 +0400 Subject: [PATCH 42/49] docs: align endpoint removal design status --- docs/design/endpoint-removal.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/design/endpoint-removal.md b/docs/design/endpoint-removal.md index 5a73e9a5..31632654 100644 --- a/docs/design/endpoint-removal.md +++ b/docs/design/endpoint-removal.md @@ -10,7 +10,7 @@ Forward route inheritance intentionally carries unchanged registrations into lat Removal must be a first-class declaration, not an accidental side effect of missing imports or manual URLPattern mutation. -## Public API proposal +## Public API For decorator-registered Django endpoints: From 4f48c4e17d5f6dd972c5d3e7d19853210dadc36d Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:46:02 +0400 Subject: [PATCH 43/49] test: preserve unrelated router actions after removal --- tests/test_route_removal.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py index 30ac8c39..213ddff5 100644 --- a/tests/test_route_removal.py +++ b/tests/test_route_removal.py @@ -162,11 +162,18 @@ def test_router_removal_is_action_specific(): class OrderViewSetV1(viewsets.ViewSet): def list(self, request): - return Response({}) + return Response({"route": "list"}) + + def retrieve(self, request, pk=None): + return Response({"route": "detail", "pk": pk}) @action(detail=False, methods=["get"], url_path="archive") def archive(self, request): - return Response({}) + return Response({"route": "archive"}) + + @action(detail=False, methods=["get"]) + def availability(self, request): + return Response({"route": "availability"}) router = VersionedRouter() router.register("orders", OrderViewSetV1, version=1, basename="order") @@ -178,7 +185,9 @@ def archive(self, request): if getattr(pattern, registry._LOGICAL_ENDPOINT_ATTR, "").startswith("orders:") } assert "order-list" in active + assert "order-detail" in active assert "order-archive" in active + assert "order-availability" in active urlconf = ModuleType("route_removal_test_urls") urlconf.urlpatterns = router.urls clear_url_caches() @@ -187,6 +196,11 @@ def archive(self, request): client = APIClient() assert client.get("/api/v2/orders/archive/").status_code == 200 assert client.get("/api/v3/orders/").status_code == 200 + assert client.get("/api/v3/orders/42/").json() == { + "route": "detail", + "pk": "42", + } + assert client.get("/api/v3/orders/availability/").status_code == 200 assert client.get("/api/v3/orders/archive/").status_code == 404 assert all( From a6deaaf7b3df0707a13377748cf904c5c01769ce Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:57:42 +0400 Subject: [PATCH 44/49] test: avoid detail-route collision in action removal test --- tests/test_route_removal.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py index 213ddff5..12cf50bc 100644 --- a/tests/test_route_removal.py +++ b/tests/test_route_removal.py @@ -167,8 +167,8 @@ def list(self, request): def retrieve(self, request, pk=None): return Response({"route": "detail", "pk": pk}) - @action(detail=False, methods=["get"], url_path="archive") - def archive(self, request): + @action(detail=True, methods=["get"], url_path="archive") + def archive(self, request, pk=None): return Response({"route": "archive"}) @action(detail=False, methods=["get"]) @@ -194,14 +194,14 @@ def availability(self, request): with override_settings(ROOT_URLCONF=urlconf): client = APIClient() - assert client.get("/api/v2/orders/archive/").status_code == 200 + assert client.get("/api/v2/orders/42/archive/").status_code == 200 assert client.get("/api/v3/orders/").status_code == 200 assert client.get("/api/v3/orders/42/").json() == { "route": "detail", "pk": "42", } assert client.get("/api/v3/orders/availability/").status_code == 200 - assert client.get("/api/v3/orders/archive/").status_code == 404 + assert client.get("/api/v3/orders/42/archive/").status_code == 404 assert all( getattr(pattern, registry._ROUTE_VERSION_ATTR) < 3 From 0468c75cf9ce64e744d18f166ecffbcca6720c23 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 19:59:16 +0400 Subject: [PATCH 45/49] style: fix route removal test spacing --- tests/test_route_removal.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py index 12cf50bc..09a2da4e 100644 --- a/tests/test_route_removal.py +++ b/tests/test_route_removal.py @@ -264,7 +264,6 @@ def test_check_versions_displays_explicit_removed_state(): assert "" in output.getvalue() - @pytest.mark.parametrize("prefix", ["/orders", "orders/"]) def test_router_remove_rejects_non_normalized_prefix(prefix): from django_api_versioning.routers import VersionedRouter From 5c237dea97835c2ea3620ae25247c21337d2ad22 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 20:11:58 +0400 Subject: [PATCH 46/49] fix: sort route removal test imports --- tests/test_route_removal.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_route_removal.py b/tests/test_route_removal.py index 09a2da4e..e5da3ae7 100644 --- a/tests/test_route_removal.py +++ b/tests/test_route_removal.py @@ -8,7 +8,7 @@ from django.urls import NoReverseMatch, clear_url_caches from django_api_versioning import api_reverse, endpoint, remove_endpoint -from django_api_versioning.exceptions import VersionMatrixError, VersioningError +from django_api_versioning.exceptions import VersioningError, VersionMatrixError from django_api_versioning.registry import registry from django_api_versioning.testing import assert_version_matrix, build_version_matrix From 248cbb4db34667dc5f7a541092f2094b43e54ea1 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 20:12:46 +0400 Subject: [PATCH 47/49] docs: tighten negotiation cache safety contract --- docs/design/request-version-resolution.md | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/docs/design/request-version-resolution.md b/docs/design/request-version-resolution.md index 6350d47a..da6d5d56 100644 --- a/docs/design/request-version-resolution.md +++ b/docs/design/request-version-resolution.md @@ -152,10 +152,21 @@ A reverse call without an explicit version may use only a configured default. It ### 4.7 Caching and security -Header-selected responses must include `Vary: Accept-Version`. Tenant-specific version selection must also account for the tenant dimension in the application's cache key and vary policy. The package must not allow a shared cache to serve one tenant's effective-version response to another tenant. +Header-selected responses must include `Vary: Accept-Version`. That response header is part of HTTP's cache-selection contract, but it is not a substitute for configuring every CDN or reverse proxy correctly: the cache must honor the nominated header and include it in its cache key. A CDN configuration that ignores `Vary` or does not forward/cache on `Accept-Version` can still serve the wrong representation. + +Query-selected responses use distinct request target URIs, but deployments must not assume that every CDN includes query strings in its cache key. For example, CloudFront cache policies can exclude all query strings or include only selected names. The configured `version` parameter must be included in the cache key and forwarded to the origin whenever query mode is used. + +Tenant-specific version selection must also account for the tenant dimension in the application's cache key and vary policy. A tenant identifier should not be trusted merely because it appears in a client-controlled header. If a trusted tenant context cannot be represented safely in the shared cache key, tenant-specific responses must bypass shared caching or be marked private. The package must not allow a shared cache to serve one tenant's effective-version response to another tenant. The resolver must consume trusted server-side context. A client-supplied version is a request, not authorization to access a tenant's version. Resolver outcomes must be validated against the global version range and the endpoint's registered implementations. +Implementation acceptance tests must verify the response's `Vary` behavior and tenant isolation at the application boundary. CDN cache-key configuration remains a deployment responsibility and must be covered by the consumer's infrastructure tests or deployment checklist. + +References: +- [RFC 9111: HTTP Caching, cache keys and Vary](https://www.rfc-editor.org/rfc/rfc9111.html) +- [Cloudflare: Vary and cache-key behavior](https://developers.cloudflare.com/cache/concepts/vary/) +- [Amazon CloudFront: cache policy and query-string cache keys](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cache-key-understand-cache-policy.html) + ## 5. Explicit non-goals The package will not become a serializer transformation framework. It will not promise automatic compatibility for response fields, validation semantics, ORM models, database migrations, or generated OpenAPI schemas. Applications remain responsible for the data contract implemented by each view. From a00498301d1e14ef8621c999f31a6c09b6d9dde8 Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 20:13:44 +0400 Subject: [PATCH 48/49] docs: correct OpenAPI contract implementation status --- docs/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/README.md b/docs/README.md index ca9a25a2..32eddcd3 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,7 +55,7 @@ The files in `articles/` are the only editable article sources. Each article's f ### OpenAPI contract and schema compatibility -- [Executable versioned OpenAPI contract example](../examples/openapi_contract/README.md): a real consumer project that generates and validates one drf-spectacular schema per VersionedRouter API version, checks serializer selection, inherited actions, and deterministic output. Schema snapshots and semantic breaking-change CI are a separate follow-up; this example does not imply that route-matrix checks prove response compatibility. +- [Executable versioned OpenAPI contract example](../examples/openapi_contract/README.md): a real consumer project that generates and validates one drf-spectacular schema per VersionedRouter API version, checks serializer selection, inherited actions, explicit endpoint removal, runtime 404 behavior, and deterministic output. The committed per-version schema baselines and `oasdiff breaking` CI gate are implemented. This does not imply that route-matrix checks or schema diffs prove business-level response compatibility. ### Routing operations and API compatibility From 7666fbba71545e3146428cac329106f8ca29f18d Mon Sep 17 00:00:00 2001 From: Mojtaba Arvin Date: Wed, 18 Nov 2026 20:13:50 +0400 Subject: [PATCH 49/49] docs: distinguish legacy Django matrix from supported releases --- docs/articles/024-django-api-versioning-supported-versions.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/articles/024-django-api-versioning-supported-versions.md b/docs/articles/024-django-api-versioning-supported-versions.md index 20757f26..dbde1a1e 100644 --- a/docs/articles/024-django-api-versioning-supported-versions.md +++ b/docs/articles/024-django-api-versioning-supported-versions.md @@ -136,6 +136,10 @@ These classifiers describe the versions associated with the package metadata. Th The actual Django version installed during a test run depends on the dependency constraints and the versions resolved by pip at that time. +The compatibility matrix still includes Django 4.2 to detect regressions for existing installations, but that does not make 4.2 a supported production target today. Django 4.2 reached the end of extended support on 7 April 2026 and no longer receives security fixes. For new deployments, choose a currently supported Django series; Django 5.2 is the current LTS line and has extended support through April 2028. Django 6.0 and 6.1 are also currently supported, with shorter support windows. + +Check Django's [live supported-versions table](https://www.djangoproject.com/download/) before selecting a deployment version, because support windows change independently of this package's CI matrix. The Django team explicitly [announced the end of Django 4.2 extended support](https://www.djangoproject.com/weblog/2026/apr/07/security-releases/) and recommends upgrading to Django 5.2 or later. + ## What Do GitHub Actions and tox Actually Test? The repository has separate workflows for the focused Python test suites and the broader Python/Django compatibility matrix. They serve different purposes and should not be treated as the same test configuration.