Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
42ef9b7
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
6cfd43e
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
4bb5108
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
ed57272
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
e87193a
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
fb5b04b
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
e079569
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
3dbb20e
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
c36c1ac
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
598bd87
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
265c967
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
65fb3b5
feat: implement explicit endpoint removal
mojtaba-arvin Nov 18, 2026
b9cc312
fix: preserve lazy DRF router import with route removal
mojtaba-arvin Nov 18, 2026
7189f4a
docs: mark 1.1.0 as the current stable release
mojtaba-arvin Nov 18, 2026
fd94c34
style: satisfy Black for endpoint tombstone registry
mojtaba-arvin Nov 18, 2026
098371f
style: fix import grouping in endpoint removal tests
mojtaba-arvin Nov 18, 2026
d7f1a64
test(openapi): remove a versioned action from v2
mojtaba-arvin Nov 18, 2026
0d54817
test(openapi): add a removable legacy action fixture
mojtaba-arvin Nov 18, 2026
d68a183
test(openapi): assert removed actions stay out of v2 schema
mojtaba-arvin Nov 18, 2026
31a5f32
style: align optional DRF test imports with isort sections
mojtaba-arvin Nov 18, 2026
d8f6d5c
test(openapi): avoid collision with detail route in removal fixture
mojtaba-arvin Nov 18, 2026
8014fa0
test(openapi): verify nested legacy action removal path
mojtaba-arvin Nov 18, 2026
34ae69d
ci(openapi): publish candidate schemas before contract verification
mojtaba-arvin Nov 18, 2026
1ae0470
ci(openapi): keep a single pre-verification schema artifact upload
mojtaba-arvin Nov 18, 2026
4dd42d0
ci(lint): print actionable isort diffs on failure
mojtaba-arvin Nov 18, 2026
617c343
test(openapi): baseline v1 legacy action before v2 removal
mojtaba-arvin Nov 18, 2026
35142b8
docs(openapi): explain the version-specific removal example
mojtaba-arvin Nov 18, 2026
f732742
docs(changelog): record explicit endpoint removal
mojtaba-arvin Nov 18, 2026
59305ad
ci(matrix): use a bounded compatibility smoke matrix on pull requests
mojtaba-arvin Nov 18, 2026
f346f17
ci(gate): select bounded compatibility checks for pull requests
mojtaba-arvin Nov 18, 2026
5b91499
ci(matrix): split PR smoke checks from the full compatibility matrix
mojtaba-arvin Nov 18, 2026
2b8a501
ci(matrix): validate full and PR smoke matrices independently
mojtaba-arvin Nov 18, 2026
9601226
style(matrix): format matrix validation diagnostics
mojtaba-arvin Nov 18, 2026
fb71068
test(lifecycle): configure a deprecated v1 contract example
mojtaba-arvin Nov 18, 2026
ce0d37f
test(lifecycle): assert deprecation and sunset response headers
mojtaba-arvin Nov 18, 2026
7bf6838
docs(openapi): distinguish endpoint removal from version retirement
mojtaba-arvin Nov 18, 2026
bdef192
docs(design): mark endpoint removal contract implemented
mojtaba-arvin Nov 18, 2026
9694a9d
docs(readme): retain the executable OpenAPI contract example link
mojtaba-arvin Nov 18, 2026
d88ba26
ci(openapi): fail if generated schema artifacts are missing
mojtaba-arvin Nov 18, 2026
3b88776
fix: validate endpoint removal router prefixes
mojtaba-arvin Nov 18, 2026
d25e706
test: cover invalid router removal declarations
mojtaba-arvin Nov 18, 2026
3815c20
docs: align endpoint removal design status
mojtaba-arvin Nov 18, 2026
4f48c4e
test: preserve unrelated router actions after removal
mojtaba-arvin Nov 18, 2026
a6deaaf
test: avoid detail-route collision in action removal test
mojtaba-arvin Nov 18, 2026
0468c75
style: fix route removal test spacing
mojtaba-arvin Nov 18, 2026
5c237de
fix: sort route removal test imports
mojtaba-arvin Nov 18, 2026
248cbb4
docs: tighten negotiation cache safety contract
mojtaba-arvin Nov 18, 2026
a004983
docs: correct OpenAPI contract implementation status
mojtaba-arvin Nov 18, 2026
7666fbb
docs: distinguish legacy Django matrix from supported releases
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
60 changes: 59 additions & 1 deletion .github/workflows/compatibility.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -88,6 +103,7 @@ jobs:
needs: validate-matrix
name: ${{ matrix.env }}
runs-on: ubuntu-latest
if: inputs.scope != 'pull-request'
timeout-minutes: 30
strategy:
fail-fast: false
Expand Down Expand Up @@ -150,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 }}
21 changes: 11 additions & 10 deletions .github/workflows/openapi-contract.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,22 @@ 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: error
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"
Expand Down Expand Up @@ -70,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
2 changes: 2 additions & 0 deletions .github/workflows/pull-request-gate.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
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
113 changes: 113 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,23 @@ 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 +215,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 +238,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
19 changes: 19 additions & 0 deletions django_api_versioning/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,25 @@ 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):
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)

@staticmethod
def _validate_version(version: int) -> None:
if isinstance(version, bool) or not isinstance(version, int):
Expand Down
Loading
Loading