Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
2ff51b3
fix: resolve lifecycle policy from matched routes
mojtaba-arvin Nov 18, 2026
4b34674
feat: resolve route versions from Django resolver routes
mojtaba-arvin Nov 18, 2026
4c70cbf
test: prefer resolved route over request version
mojtaba-arvin Nov 18, 2026
4bc6b44
docs: define resolver-aware lifecycle behavior
mojtaba-arvin Nov 18, 2026
e8e7b54
test: cover resolver-aware lifecycle middleware end to end
mojtaba-arvin Nov 18, 2026
bcfb51f
fix: normalize regex routes during version resolution
mojtaba-arvin Nov 18, 2026
eb686b7
test: clear request version before path fallback assertion
mojtaba-arvin Nov 18, 2026
29410d9
test: assert DRF resolver route metadata
mojtaba-arvin Nov 18, 2026
faccd68
style: keep route version matcher within line limits
mojtaba-arvin Nov 18, 2026
91b74e8
docs: refresh lifecycle source evidence anchors
mojtaba-arvin Nov 18, 2026
04fbaf9
test: clarify lifecycle version precedence
mojtaba-arvin Nov 18, 2026
6dce1c8
fix: normalize resolver regex anchors on both routes
mojtaba-arvin Nov 18, 2026
e65c1b0
style: format lifecycle version collection
mojtaba-arvin Nov 18, 2026
8bf52a1
style: wrap lifecycle source symbol reference
mojtaba-arvin Nov 18, 2026
eafd1a5
test: assert the new pre-view sunset evidence
mojtaba-arvin Nov 18, 2026
6ebe78a
refactor: isolate resolver lookup from tombstone registry changes
mojtaba-arvin Nov 18, 2026
684e927
test: cover request-level URLconf lifecycle resolution
mojtaba-arvin Nov 18, 2026
82d9ac6
style: separate lifecycle integration test functions
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
181 changes: 108 additions & 73 deletions django_api_versioning/lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.conf import settings as django_settings
from django.http import HttpRequest, HttpResponse, HttpResponseGone

from .registry import registry
from .settings import api_settings

logger = logging.getLogger(__name__)
Expand All @@ -21,13 +22,9 @@ def _get_api_setting(name: str, default: Any = None) -> Any:

Falls back to default if setting is not configured in either location.
"""
# First, check if the setting exists in django.conf.settings
# This handles override_settings() and other dynamic setting changes
if hasattr(django_settings, name):
return getattr(django_settings, name)

# Fall back to cached api_settings for backward compatibility with tests
# that use monkeypatch to modify api_settings directly
if hasattr(api_settings, name):
return getattr(api_settings, name)

Expand All @@ -36,52 +33,63 @@ def _get_api_setting(name: str, default: Any = None) -> Any:

class LifecycleMiddleware:
"""
Inject ``Deprecation`` / ``Sunset`` headers and enforce sunset.

Configure via ``API_VERSION_LIFECYCLE``::

API_VERSION_LIFECYCLE = {
1: {"status": "retired", "sunset": "2024-01-01"},
2: {
"status": "deprecated",
"deprecated_at": "2026-01-01T00:00:00+00:00",
"sunset": "2026-06-01",
},
3: {"status": "active"},
}
Inject Deprecation / Sunset headers and enforce version-wide sunset.

Resolved requests use Django's actual resolver match. Unresolved requests
retain path-based lifecycle behavior only when the API version is
unambiguous.
"""

def __init__(self, get_response: Callable) -> None:
self.get_response = get_response

def __call__(self, request: HttpRequest) -> HttpResponse:
version = _extract_version(request)
if version is None:
return self.get_response(request)
response = self.get_response(request)
return self.process_response(request, response)

def process_view(
self,
request: HttpRequest,
view_func: Callable,
view_args: list,
view_kwargs: dict,
) -> HttpResponse | None:
"""Enforce sunset after URL resolution and before the selected view."""
state = _get_lifecycle_state(request)
if state is None:
return None

version, meta, _, sunset_date = state
if not meta or sunset_date is None or not _is_past(sunset_date):
return None

request._django_api_version_lifecycle_sunset_enforced = True
sunset = meta.get("sunset")
return HttpResponseGone(
f"API version {version} has been retired as of {sunset}."
)

def process_response(
self, request: HttpRequest, response: HttpResponse
) -> HttpResponse:
"""Apply lifecycle headers or preserve version-wide 410 behavior."""
state = _get_lifecycle_state(request)
if state is None:
return response

lifecycle = _get_api_setting("API_VERSION_LIFECYCLE", {})
meta = lifecycle.get(version)
version, meta, deprecation_date, sunset_date = state
if not meta:
return self.get_response(request)
return response

deprecated_at = meta.get("deprecated_at")
deprecation_date = (
_parse_lifecycle_date(deprecated_at, "deprecation")
if deprecated_at
else None
)
sunset = meta.get("sunset")
sunset_date = _parse_sunset(sunset) if sunset else None
if sunset_date and _is_past(sunset_date):
if sunset_date is not None and _is_past(sunset_date):
if getattr(request, "_django_api_version_lifecycle_sunset_enforced", False):
return response
sunset = meta.get("sunset")
return HttpResponseGone(
f"API version {version} has been retired as of {sunset}."
)

response = self.get_response(request)
status = meta.get("status")
# A retired version whose sunset is still in the future is still served
# (past sunsets returned 410 above), so clients must be warned about the
# upcoming removal exactly like for a deprecated version.
if status in ("deprecated", "retired"):
if deprecation_date is not None:
response["Deprecation"] = _to_structured_field_date(deprecation_date)
Expand All @@ -96,6 +104,36 @@ def __call__(self, request: HttpRequest) -> HttpResponse:
return response


def _get_lifecycle_state(
request: HttpRequest,
) -> tuple[int, dict | None, datetime | None, datetime | None] | None:
"""Resolve and cache lifecycle metadata once per request."""
if hasattr(request, "_django_api_version_lifecycle_state"):
return request._django_api_version_lifecycle_state

version = _extract_version(request)
if version is None:
return None

lifecycle = _get_api_setting("API_VERSION_LIFECYCLE", {})
meta = lifecycle.get(version)
if not meta:
state = (version, None, None, None)
else:
deprecated_at = meta.get("deprecated_at")
deprecation_date = (
_parse_lifecycle_date(deprecated_at, "deprecation")
if deprecated_at
else None
)
sunset = meta.get("sunset")
sunset_date = _parse_sunset(sunset) if sunset else None
state = (version, meta, deprecation_date, sunset_date)

request._django_api_version_lifecycle_state = state
return state


def _coerce_version(value: Any) -> int | None:
"""Accept integer versions without truncating booleans or other numeric types."""
if isinstance(value, bool):
Expand All @@ -108,63 +146,62 @@ def _coerce_version(value: Any) -> int | None:


def _extract_version(request: HttpRequest) -> int | None:
# Path-based: request.version is set by DRF or by URLPathVersioning.
version = _coerce_version(getattr(request, "version", None))
if version is not None:
return version

# Fallback: parse from resolver_match kwargs.
"""Prefer the actual matched route over request/path heuristics."""
match = getattr(request, "resolver_match", None)
if match:
version = _coerce_version(match.kwargs.get("version"))
kwargs = getattr(match, "kwargs", {}) or {}
version = _coerce_version(kwargs.get("version"))
if version is not None:
return version

# Fallback: extract from static URL path using API_BASE_PATH pattern.
route = getattr(match, "route", None)
if isinstance(route, str):
version = registry.get_resolved_route_version(route)
if version is not None:
return _coerce_version(version)
version = _extract_version_from_value(route)
if version is not None:
return version

# Retain support for explicitly supplied request.version when no matched
# route metadata identifies a version.
version = _coerce_version(getattr(request, "version", None))
if version is not None:
return version

# Unresolved requests use a conservative path fallback. Multiple distinct
# version segments are ambiguous and must not select the wrong policy.
return _extract_version_from_path(request)


def _extract_version_from_path(request: HttpRequest) -> int | None:
"""
Extract API version from static URL paths generated by @endpoint.
Extract an unambiguous version from a static URL path.

For example, with API_BASE_PATH = "api/v{version}/", a request to
/api/v2/users/ will extract version 2.

Returns None if no valid version is found.
This fallback is used for unresolved requests. A resolved request uses
ResolverMatch and registry route metadata instead.
"""
api_base_path = _get_api_setting("API_BASE_PATH", "api/v{version}/")
if not api_base_path or "{version}" not in api_base_path:
return None

# Get the request path (without query string)
path = request.path_info or request.path or ""
return _extract_version_from_value(path)

# Build regex pattern from API_BASE_PATH
# Split on {version}, escape each part, then rejoin with version pattern
parts = api_base_path.split("{version}")
if len(parts) != 2:

def _extract_version_from_value(value: str) -> int | None:
"""Extract one distinct version from a path or resolved route string."""
api_base_path = _get_api_setting("API_BASE_PATH", "api/v{version}/")
if not api_base_path or api_base_path.count("{version}") != 1:
return None

# Escape regex special characters in each part
prefix = re.escape(parts[0])
parts = api_base_path.split("{version}")
prefix = re.escape(parts[0].lstrip("/"))
suffix = re.escape(parts[1])

# The API may be mounted below a parent URL prefix via include(). Match
# API_BASE_PATH at a path-segment boundary rather than only at path start.
# This still avoids false positives such as "notapi/v2/".
prefix = prefix.lstrip("/")
pattern = f"(?:^|/){prefix}(\\d+){suffix}"

try:
regex_match = re.search(pattern, path)
if regex_match:
version_str = regex_match.group(1)
return int(version_str)
versions = {int(match.group(1)) for match in re.finditer(pattern, value)}
except (IndexError, ValueError, re.error):
pass
return None

return None
return next(iter(versions)) if len(versions) == 1 else None


def _parse_sunset(value: Any) -> datetime | None:
Expand All @@ -179,8 +216,6 @@ def _parse_lifecycle_date(value: Any, field_name: str) -> datetime | None:
return None

try:
# datetime.fromisoformat() only accepted the ISO 8601 UTC "Z" suffix
# starting with Python 3.11; normalize it for the Python 3.10 floor.
normalized_value = value[:-1] + "+00:00" if value.endswith("Z") else value
parsed = datetime.fromisoformat(normalized_value)
except ValueError:
Expand Down
45 changes: 45 additions & 0 deletions django_api_versioning/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,51 @@ def _find_route_index(self, route: str) -> int | None:

return None

def get_resolved_route_version(self, route: str) -> int | None:
"""Resolve a version from the longest registered route suffix.

Django's ResolverMatch.route includes every parent URLResolver prefix.
Matching a registered route as a complete suffix therefore supports
nested includes without confusing a parent API-like prefix for the
child endpoint's version.
"""
matches: list[tuple[int, int]] = []
route_variants = {
route,
route.removeprefix("^").removesuffix("$"),
}
for pattern in self.urlpatterns:
registered_pattern = str(pattern.pattern)
pattern_variants = {
registered_pattern,
registered_pattern.removeprefix("^").removesuffix("$"),
}

matched_length = 0
for route_candidate in route_variants:
for pattern_candidate in pattern_variants:
start = len(route_candidate) - len(pattern_candidate)
if start < 0 or route_candidate[start:] != pattern_candidate:
continue
if start and route_candidate[start - 1] != "/":
continue
matched_length = max(matched_length, len(pattern_candidate))

version = getattr(pattern, self._ROUTE_VERSION_ATTR, None)
if (
matched_length
and isinstance(version, int)
and not isinstance(version, bool)
):
matches.append((matched_length, version))

if not matches:
return None

longest = max(length for length, _ in matches)
versions = {version for length, version in matches if length == longest}
return next(iter(versions)) if len(versions) == 1 else None

def _should_replace(
self,
existing_pattern: URLPattern,
Expand Down
6 changes: 5 additions & 1 deletion docs/reference/versioning-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,11 @@ Settings validation requires `deprecated_at` for deprecated versions and rejects

A `retired` version whose sunset date is still in the future is still served. Its responses carry the `Sunset` header, and also the `Deprecation` header when `deprecated_at` is configured; unlike for `deprecated` versions, a missing `deprecated_at` is not logged as a problem. `active` and unknown versions never receive lifecycle headers.

This is a version-wide policy. The middleware also recognizes the configured API base path below parent URL prefixes, so lifecycle headers continue to work when a versioned router is mounted through nested URL includes. It does not generate migration links or resource-specific successor URLs; applications must provide those when needed.
This is a version-wide policy. For a resolved request, the middleware uses Django's actual resolver match and the registered route metadata, including the full route contributed by parent URL includes. A parent path that happens to contain another API-like version segment cannot override the version of the child endpoint that Django selected.

For a request that does not resolve to a view, the middleware retains path-based lifecycle behavior only when the configured API base path identifies exactly one distinct version. If an unresolved path contains multiple different version segments, the version is ambiguous and the middleware does not guess; the unresolved request remains a 404 rather than receiving a potentially incorrect 410. A resolved view's own 404 response still receives the matched version's lifecycle headers.

The middleware does not generate migration links or resource-specific successor URLs; applications must provide those when needed.

## 13. Scope and known limitations

Expand Down
9 changes: 8 additions & 1 deletion integration_test_project/segment_lab/generate_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,10 @@ def provenance() -> dict:
"Command._warn_gaps",
),
"LifecycleMiddleware.__call__": ("lifecycle.py", "LifecycleMiddleware.__call__"),
"LifecycleMiddleware.process_view": (
"lifecycle.py",
"LifecycleMiddleware.process_view",
),
"_extract_version_from_path": ("lifecycle.py", "_extract_version_from_path"),
"_parse_sunset": ("lifecycle.py", "_parse_sunset"),
"build_version_matrix": ("testing.py", "build_version_matrix"),
Expand Down Expand Up @@ -232,7 +236,10 @@ def provenance() -> dict:
"management/commands/check_versions.py",
"callback_name = self._get_callback_name(versions[version])",
),
"sunset_410": ("lifecycle.py", "if sunset_date and _is_past(sunset_date):"),
"sunset_410": (
"lifecycle.py",
"request._django_api_version_lifecycle_sunset_enforced = True",
),
"deprecated_header": ("lifecycle.py", 'if status in ("deprecated", "retired"):'),
"reverse_ambiguous": ("reverse.py", "if version is None and len(matches) > 1:"),
}
Expand Down
2 changes: 1 addition & 1 deletion integration_test_project/segment_lab/test_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def test_source_references_resolve_against_current_package() -> None:
assert "LifecycleMiddleware.__call__" in refs["symbols"]
assert "_parse_sunset" in refs["symbols"]
assert refs["lines"]["sunset_410"]["code"] == (
"if sunset_date and _is_past(sunset_date):"
"request._django_api_version_lifecycle_sunset_enforced = True"
)
assert refs["lines"]["gap_warning"]["code"] == (
'self.style.WARNING(f" [{endpoint}] v{v} is not defined.")'
Expand Down
16 changes: 9 additions & 7 deletions tests/test_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,26 +401,28 @@ def test_extract_version_no_resolver_match(self):
assert version == 1

def test_extract_version_precedence_order(self):
"""Verifies version extraction precedence: request.version > kwargs > path."""
"""Verifies resolver metadata > request.version > path fallback precedence."""
from unittest.mock import Mock

from django_api_versioning.lifecycle import _extract_version

# When all three are set, request.version wins
# A version captured by the actual resolver wins over an unrelated
# request.version value; the route selected by Django is authoritative.
request = RequestFactory().get("/api/v1/users/")
request.version = "5"
request.resolver_match = Mock()
request.resolver_match.kwargs = {"version": "3"}
version = _extract_version(request)
assert version == 5
assert version == 3

# When request.version is None, kwargs wins
request.version = None
# Without resolver version metadata, request.version remains a fallback.
request.resolver_match.kwargs = {}
version = _extract_version(request)
assert version == 3
assert version == 5

# When both are None, path wins
# When resolver metadata and request.version are both absent, path wins.
request.resolver_match.kwargs = {}
request.version = None
version = _extract_version(request)
assert version == 1

Expand Down
Loading
Loading