Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
d251af9
docs: specify explicit endpoint removal semantics
mojtaba-arvin Nov 18, 2026
3372b71
test: define explicit route removal contract
mojtaba-arvin Nov 18, 2026
d87e0f5
feat: add registry tombstones for explicit route removal
mojtaba-arvin Nov 18, 2026
750fa2c
fix: apply tombstones to router-generated URL patterns
mojtaba-arvin Nov 18, 2026
d490ea2
feat: expose explicit endpoint and ViewSet route removal
mojtaba-arvin Nov 18, 2026
2bfc929
feat: expose explicit endpoint and ViewSet route removal
mojtaba-arvin Nov 18, 2026
7083a5a
feat: expose explicit endpoint and ViewSet route removal
mojtaba-arvin Nov 18, 2026
23cd3ea
feat: expose explicit endpoint and ViewSet route removal
mojtaba-arvin Nov 18, 2026
8e3d51e
feat: expose explicit endpoint and ViewSet route removal
mojtaba-arvin Nov 18, 2026
ef47fb8
feat: expose explicit endpoint and ViewSet route removal
mojtaba-arvin Nov 18, 2026
b6cbb4b
feat: expose explicit endpoint and ViewSet route removal
mojtaba-arvin Nov 18, 2026
e39214c
style: remove unused route test import
mojtaba-arvin Nov 18, 2026
36ed0ed
fix: preserve unique website source anchor and format registry
mojtaba-arvin Nov 18, 2026
296dae2
style: format endpoint removal regression tests
mojtaba-arvin Nov 18, 2026
36f3ad3
test: cover removal snapshots and action-level 404 behavior
mojtaba-arvin Nov 18, 2026
235ca20
chore: preview Black formatting for removal implementation
mojtaba-arvin Nov 18, 2026
70d0cca
fix: keep route source anchor unique for website generator
mojtaba-arvin Nov 18, 2026
702559c
style: correct spacing in removal tests
mojtaba-arvin Nov 18, 2026
fb053a4
style: apply Black formatting to registry
mojtaba-arvin Nov 18, 2026
e502f60
style: apply Black formatting to route removal tests
mojtaba-arvin Nov 18, 2026
a51027c
chore: remove temporary formatter preview command
mojtaba-arvin Nov 18, 2026
5457f2b
docs: document explicit endpoint removal contract
mojtaba-arvin Nov 18, 2026
f5d64fe
docs: document explicit endpoint removal contract
mojtaba-arvin Nov 18, 2026
d1be70d
docs: document explicit endpoint removal contract
mojtaba-arvin Nov 18, 2026
b704472
fix: preserve active route state when a path is reused
mojtaba-arvin Nov 18, 2026
1f5eecc
test: preserve active state when a tombstoned path is reused
mojtaba-arvin Nov 18, 2026
1811598
style: normalize spacing in route reuse regression test
mojtaba-arvin Nov 18, 2026
503a9c2
docs: align tombstone source-version precedence
mojtaba-arvin Nov 18, 2026
a34a8c7
test: verify check_versions reports removed routes
mojtaba-arvin Nov 18, 2026
4fdc05b
style: apply Black formatting to removal registry
mojtaba-arvin Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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**.
Expand Down
4 changes: 2 additions & 2 deletions django_api_versioning/__init__.py
Original file line number Diff line number Diff line change
@@ -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"]
18 changes: 18 additions & 0 deletions django_api_versioning/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
4 changes: 3 additions & 1 deletion django_api_versioning/management/commands/check_versions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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 "<removed>"
# Try to get from class-based view metadata first
if hasattr(callback, "view_class"):
return callback.view_class.__name__
Expand Down
111 changes: 111 additions & 0 deletions django_api_versioning/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]


Expand All @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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]]:
Expand All @@ -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:
Expand Down
12 changes: 12 additions & 0 deletions django_api_versioning/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,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):
Expand Down
4 changes: 3 additions & 1 deletion django_api_versioning/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 "<removed>"
view_class = getattr(callback, "view_class", None)
if view_class is not None:
return view_class.__name__
Expand Down
94 changes: 94 additions & 0 deletions docs/design/endpoint-removal.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading