django-api-versioning 0.3.5__tar.gz → 0.3.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/CHANGELOG.md +19 -0
  2. {django_api_versioning-0.3.5/django_api_versioning.egg-info → django_api_versioning-0.3.6}/PKG-INFO +104 -3
  3. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/README.md +103 -2
  4. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/decorators.py +8 -0
  5. django_api_versioning-0.3.6/django_api_versioning/management/commands/check_versions.py +62 -0
  6. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/registry.py +53 -1
  7. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6/django_api_versioning.egg-info}/PKG-INFO +104 -3
  8. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/pyproject.toml +1 -1
  9. django_api_versioning-0.3.6/tests/test_decorators.py +429 -0
  10. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_lifecycle.py +9 -3
  11. django_api_versioning-0.3.6/tests/test_management_commands.py +358 -0
  12. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_registry.py +60 -0
  13. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_reverse.py +3 -0
  14. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_testing_utils.py +1 -1
  15. django_api_versioning-0.3.5/django_api_versioning/management/commands/check_versions.py +0 -39
  16. django_api_versioning-0.3.5/tests/test_decorators.py +0 -160
  17. django_api_versioning-0.3.5/tests/test_management_commands.py +0 -42
  18. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/LICENSE +0 -0
  19. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/MANIFEST.in +0 -0
  20. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/__init__.py +0 -0
  21. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/channels.py +0 -0
  22. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/exceptions.py +0 -0
  23. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/lifecycle.py +0 -0
  24. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/management/__init__.py +0 -0
  25. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/management/commands/__init__.py +0 -0
  26. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/management/commands/migrate_endpoints.py +0 -0
  27. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/reverse.py +0 -0
  28. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/settings.py +0 -0
  29. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/testing.py +0 -0
  30. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning/urls.py +0 -0
  31. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning.egg-info/SOURCES.txt +0 -0
  32. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning.egg-info/dependency_links.txt +0 -0
  33. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning.egg-info/requires.txt +0 -0
  34. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/django_api_versioning.egg-info/top_level.txt +0 -0
  35. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/pytest.ini +0 -0
  36. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/requirements-dev.txt +0 -0
  37. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/requirements.txt +0 -0
  38. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/setup.cfg +0 -0
  39. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/__init__.py +0 -0
  40. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/conftest.py +0 -0
  41. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/settings.py +0 -0
  42. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_channels.py +0 -0
  43. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_channels_extra.py +0 -0
  44. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_exceptions.py +0 -0
  45. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_segment_model.py +0 -0
  46. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_settings.py +0 -0
  47. {django_api_versioning-0.3.5 → django_api_versioning-0.3.6}/tests/test_urls.py +0 -0
@@ -8,6 +8,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.3.6] - 2026-11-13
12
+
13
+ ### Fixed
14
+
15
+ - **Logical endpoint matrix grouping:** Fixed `check_versions` output grouping physical URL patterns by logical endpoint identity instead of individual versioned routes. Multiple versions of the same endpoint (e.g., `/api/v1/users/`, `/api/v2/users/`, `/api/v3/users/`) now appear under a single logical endpoint heading, eliminating false missing-version warnings for inherited routes.
16
+ - **Class-based view callback names:** Fixed `check_versions` display of callback names for Django class-based views, DRF APIViews, and DRF ViewSets. Previously displayed generic "view" for all class-based views; now resolves `view_class.__name__` or `cls.__name__` to show meaningful class names.
17
+ - **ViewSet registration error message:** Improved error handling for DRF ViewSet registration without action configuration. Now raises clear TypeError with actionable guidance (`ViewSet 'MyViewSet' cannot be registered directly. Pass a configured callable like: MyViewSet.as_view({'get': 'list', ...})`) instead of obscure raw DRF exception.
18
+
19
+ ### Added
20
+
21
+ - **Improved management command tests:** Replaced weak assertions with meaningful test coverage: empty registry produces "No endpoints registered" message, registered endpoints display correctly with versions and callback names, logical endpoint grouping works without false gaps, internal version gaps are detected correctly.
22
+
23
+ ### Verified
24
+
25
+ - ✅ All 160 unit tests passing across Python 3.10–3.15
26
+ - ✅ All 236 integration tests passing across Python 3.10–3.15
27
+ - ✅ No DRF runtime dependency (remains dev-only)
28
+ - ✅ Backward compatibility with existing registry API maintained
29
+
11
30
  ## [0.3.5] - 2026-11-12
12
31
 
13
32
  ### Documentation
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-api-versioning
3
- Version: 0.3.5
3
+ Version: 0.3.6
4
4
  Summary: API versioning for Django and Django REST Framework (DRF), with decorator-based endpoint registration, automatic URL routing, version-specific views, and forward inheritance for backward-compatible API evolution.
5
5
  Author-email: Mojtaba Arvin <ArvinDevDay@gmail.com>
6
6
  License: MIT
@@ -631,6 +631,47 @@ Prints registered routes, their route versions, and the associated callback name
631
631
 
632
632
  Use it to inspect the routing result after adding or changing endpoint declarations.
633
633
 
634
+ **Output interpretation:**
635
+
636
+ The command groups routes by their *logical endpoint* (the path without versioning), not by physical URL. This means:
637
+
638
+ ```text
639
+ users/:
640
+ v1 → users_list_v1
641
+ v2 → users_list_v2
642
+ v3 → users_list_v2
643
+ v4 → users_list_v2
644
+ ```
645
+
646
+ Even though physical URLs are `/api/v1/users/`, `/api/v2/users/`, etc., the command groups them under the logical endpoint `users`.
647
+
648
+ **Callback name resolution:**
649
+
650
+ The command resolves callback names intelligently:
651
+
652
+ - **Function-based views:** Shows the function name (e.g., `my_view`)
653
+ - **Django View classes:** Shows the class name (e.g., `MyView`)
654
+ - **DRF APIView:** Shows the class name (e.g., `MyAPIView`)
655
+ - **DRF ViewSet actions:** Shows the ViewSet class name (e.g., `MyViewSet`)
656
+
657
+ **Gap detection:**
658
+
659
+ The command warns about missing versions within an endpoint's span:
660
+
661
+ ```text
662
+ users:
663
+ v1 → users_list_v1
664
+ v3 → users_list_v3
665
+ [users] v2 is not defined.
666
+ ```
667
+
668
+ It does NOT warn about versions before an endpoint's introduction or after its final declaration:
669
+
670
+ ```text
671
+ # No warning for v1 (starts at v2)
672
+ # No warning for v4 (ends at v3)
673
+ ```
674
+
634
675
  ### `assert_version_matrix` — guard routing changes in CI
635
676
 
636
677
  The package provides a snapshot utility for detecting unintended changes to the registered route matrix.
@@ -825,7 +866,31 @@ A generic view must implement the HTTP handlers required by its registered route
825
866
 
826
867
  A DRF `ViewSet` class cannot be passed directly to `@endpoint` as a normal class-based view. Its `as_view()` method requires an action mapping, while the package invokes `as_view()` without one.
827
868
 
828
- Use DRF routers for standard ViewSet resource routing.
869
+ To register a ViewSet action, pass a pre-configured callable:
870
+
871
+ ```python
872
+ from rest_framework.viewsets import ViewSet
873
+ from django_api_versioning import endpoint
874
+
875
+
876
+ class MyViewSet(ViewSet):
877
+ def list(self, request):
878
+ return JsonResponse({})
879
+
880
+ def create(self, request):
881
+ return JsonResponse({})
882
+
883
+
884
+ # ✓ Correct: pass a configured callable
885
+ @endpoint("items/", version=1)
886
+ def list_items(request):
887
+ return MyViewSet.as_view({"get": "list"})(request)
888
+
889
+ # ✗ Incorrect: class without action mapping
890
+ # @endpoint("items/", version=1, MyViewSet) # TypeError!
891
+ ```
892
+
893
+ For standard ViewSet resource routing (list, create, retrieve, update, destroy), use DRF routers separately.
829
894
 
830
895
  The package does not automatically generate router-style ViewSet routes.
831
896
 
@@ -839,13 +904,49 @@ It does not:
839
904
  - Select serializers based on a request version.
840
905
  - Replace DRF authentication or permission classes.
841
906
  - Replace DRF routers for ViewSet resource routing.
842
- - Automatically set `request.version`.
907
+ - Automatically set `request.version` (DRF's concern).
843
908
  - Use `API_VERSIONING_CHANNELS` to select routes.
844
909
  - Use `API_EFFECTIVE_VERSION_RESOLVER` for tenant-specific route selection.
845
910
  - Validate response payload compatibility through route-matrix checks.
846
911
 
847
912
  Your application remains responsible for API contract design, serializer selection, authentication, permissions, business logic, and request-level compatibility tests.
848
913
 
914
+ ### Package vs. DRF: Division of responsibilities
915
+
916
+ **Package responsibility: Route selection**
917
+
918
+ The package registers literal URL paths (`/api/v1/endpoint`, `/api/v2/endpoint`) and selects the correct handler based on the URL path.
919
+
920
+ **DRF responsibility: request.version**
921
+
922
+ DRF's versioning classes (like `URLPathVersioning`) populate `request.version` if configured. However, DRF's `URLPathVersioning` uses a URL resolver keyword argument named `version`, which the package does not populate. This means:
923
+
924
+ - The package successfully routes requests to version-specific handlers.
925
+ - `request.version` may be `None` unless you configure a custom versioning class.
926
+
927
+ If you need `request.version` populated, consider implementing a custom DRF versioning class that extracts the version from the URL path or adds a custom resolver keyword argument when registering routes.
928
+
929
+ ### Configuration timing
930
+
931
+ Package settings (`API_MAX_VERSION`, `API_BASE_PATH`, etc.) are validated and loaded at module import time. Using Django's `override_settings` after the package has been imported will NOT affect already-loaded configuration:
932
+
933
+ ```python
934
+ # ✓ Correct: configure before importing views
935
+ os.environ["DJANGO_SETTINGS_MODULE"] = "myapp.settings"
936
+ from django.conf import settings
937
+ settings.API_MAX_VERSION = 5
938
+ from myapp import views # Package uses the configured API_MAX_VERSION
939
+
940
+ # ✗ Incorrect: configure after importing
941
+ from django_api_versioning import api_settings
942
+ from django.test import override_settings
943
+ with override_settings(API_MAX_VERSION=5):
944
+ # This does NOT affect api_settings (already loaded)
945
+ ...
946
+ ```
947
+
948
+ Set all configuration in Django settings before importing modules containing `@endpoint` decorators.
949
+
849
950
  ## Migration from 0.2.0
850
951
 
851
952
  Version 0.3.0 replaced the previous forward/backward inheritance flags model with segment-based registration.
@@ -582,6 +582,47 @@ Prints registered routes, their route versions, and the associated callback name
582
582
 
583
583
  Use it to inspect the routing result after adding or changing endpoint declarations.
584
584
 
585
+ **Output interpretation:**
586
+
587
+ The command groups routes by their *logical endpoint* (the path without versioning), not by physical URL. This means:
588
+
589
+ ```text
590
+ users/:
591
+ v1 → users_list_v1
592
+ v2 → users_list_v2
593
+ v3 → users_list_v2
594
+ v4 → users_list_v2
595
+ ```
596
+
597
+ Even though physical URLs are `/api/v1/users/`, `/api/v2/users/`, etc., the command groups them under the logical endpoint `users`.
598
+
599
+ **Callback name resolution:**
600
+
601
+ The command resolves callback names intelligently:
602
+
603
+ - **Function-based views:** Shows the function name (e.g., `my_view`)
604
+ - **Django View classes:** Shows the class name (e.g., `MyView`)
605
+ - **DRF APIView:** Shows the class name (e.g., `MyAPIView`)
606
+ - **DRF ViewSet actions:** Shows the ViewSet class name (e.g., `MyViewSet`)
607
+
608
+ **Gap detection:**
609
+
610
+ The command warns about missing versions within an endpoint's span:
611
+
612
+ ```text
613
+ users:
614
+ v1 → users_list_v1
615
+ v3 → users_list_v3
616
+ [users] v2 is not defined.
617
+ ```
618
+
619
+ It does NOT warn about versions before an endpoint's introduction or after its final declaration:
620
+
621
+ ```text
622
+ # No warning for v1 (starts at v2)
623
+ # No warning for v4 (ends at v3)
624
+ ```
625
+
585
626
  ### `assert_version_matrix` — guard routing changes in CI
586
627
 
587
628
  The package provides a snapshot utility for detecting unintended changes to the registered route matrix.
@@ -776,7 +817,31 @@ A generic view must implement the HTTP handlers required by its registered route
776
817
 
777
818
  A DRF `ViewSet` class cannot be passed directly to `@endpoint` as a normal class-based view. Its `as_view()` method requires an action mapping, while the package invokes `as_view()` without one.
778
819
 
779
- Use DRF routers for standard ViewSet resource routing.
820
+ To register a ViewSet action, pass a pre-configured callable:
821
+
822
+ ```python
823
+ from rest_framework.viewsets import ViewSet
824
+ from django_api_versioning import endpoint
825
+
826
+
827
+ class MyViewSet(ViewSet):
828
+ def list(self, request):
829
+ return JsonResponse({})
830
+
831
+ def create(self, request):
832
+ return JsonResponse({})
833
+
834
+
835
+ # ✓ Correct: pass a configured callable
836
+ @endpoint("items/", version=1)
837
+ def list_items(request):
838
+ return MyViewSet.as_view({"get": "list"})(request)
839
+
840
+ # ✗ Incorrect: class without action mapping
841
+ # @endpoint("items/", version=1, MyViewSet) # TypeError!
842
+ ```
843
+
844
+ For standard ViewSet resource routing (list, create, retrieve, update, destroy), use DRF routers separately.
780
845
 
781
846
  The package does not automatically generate router-style ViewSet routes.
782
847
 
@@ -790,13 +855,49 @@ It does not:
790
855
  - Select serializers based on a request version.
791
856
  - Replace DRF authentication or permission classes.
792
857
  - Replace DRF routers for ViewSet resource routing.
793
- - Automatically set `request.version`.
858
+ - Automatically set `request.version` (DRF's concern).
794
859
  - Use `API_VERSIONING_CHANNELS` to select routes.
795
860
  - Use `API_EFFECTIVE_VERSION_RESOLVER` for tenant-specific route selection.
796
861
  - Validate response payload compatibility through route-matrix checks.
797
862
 
798
863
  Your application remains responsible for API contract design, serializer selection, authentication, permissions, business logic, and request-level compatibility tests.
799
864
 
865
+ ### Package vs. DRF: Division of responsibilities
866
+
867
+ **Package responsibility: Route selection**
868
+
869
+ The package registers literal URL paths (`/api/v1/endpoint`, `/api/v2/endpoint`) and selects the correct handler based on the URL path.
870
+
871
+ **DRF responsibility: request.version**
872
+
873
+ DRF's versioning classes (like `URLPathVersioning`) populate `request.version` if configured. However, DRF's `URLPathVersioning` uses a URL resolver keyword argument named `version`, which the package does not populate. This means:
874
+
875
+ - The package successfully routes requests to version-specific handlers.
876
+ - `request.version` may be `None` unless you configure a custom versioning class.
877
+
878
+ If you need `request.version` populated, consider implementing a custom DRF versioning class that extracts the version from the URL path or adds a custom resolver keyword argument when registering routes.
879
+
880
+ ### Configuration timing
881
+
882
+ Package settings (`API_MAX_VERSION`, `API_BASE_PATH`, etc.) are validated and loaded at module import time. Using Django's `override_settings` after the package has been imported will NOT affect already-loaded configuration:
883
+
884
+ ```python
885
+ # ✓ Correct: configure before importing views
886
+ os.environ["DJANGO_SETTINGS_MODULE"] = "myapp.settings"
887
+ from django.conf import settings
888
+ settings.API_MAX_VERSION = 5
889
+ from myapp import views # Package uses the configured API_MAX_VERSION
890
+
891
+ # ✗ Incorrect: configure after importing
892
+ from django_api_versioning import api_settings
893
+ from django.test import override_settings
894
+ with override_settings(API_MAX_VERSION=5):
895
+ # This does NOT affect api_settings (already loaded)
896
+ ...
897
+ ```
898
+
899
+ Set all configuration in Django settings before importing modules containing `@endpoint` decorators.
900
+
800
901
  ## Migration from 0.2.0
801
902
 
802
903
  Version 0.3.0 replaced the previous forward/backward inheritance flags model with segment-based registration.
@@ -15,6 +15,10 @@ ViewT = TypeVar("ViewT", bound=Callable)
15
15
 
16
16
  def ver_range(start: int, end: int) -> list[int]:
17
17
  """Inclusive range of API versions, e.g. ver_range(1, 3) -> [1, 2, 3]."""
18
+ if isinstance(start, bool) or not isinstance(start, int):
19
+ raise VersionTypeError("ver_range start must be an integer.")
20
+ if isinstance(end, bool) or not isinstance(end, int):
21
+ raise VersionTypeError("ver_range end must be an integer.")
18
22
  if start > end:
19
23
  raise VersionRangeError(f"ver_range start ({start}) must be <= end ({end}).")
20
24
  return list(range(start, end + 1))
@@ -71,6 +75,9 @@ def endpoint(
71
75
 
72
76
  app_name_part: str = f"{app_name}/" if app_name else ""
73
77
 
78
+ # Calculate logical endpoint ID from unversioned path
79
+ logical_endpoint = f"{app_name_part}{postfix}"
80
+
74
81
  def _register_route(ver: int | None, source_version: int | None) -> None:
75
82
  """Helper function to register a route in the registry."""
76
83
  if ver is None:
@@ -84,6 +91,7 @@ def endpoint(
84
91
  view_name,
85
92
  source_version=source_version,
86
93
  route_version=ver,
94
+ logical_endpoint=logical_endpoint,
87
95
  )
88
96
 
89
97
  if version is not None:
@@ -0,0 +1,62 @@
1
+ from collections import defaultdict
2
+
3
+ from django.core.management.base import BaseCommand
4
+
5
+ from ...registry import registry
6
+
7
+
8
+ class Command(BaseCommand):
9
+ help = "Print the API version matrix and warn about gaps."
10
+
11
+ def handle(self, *args, **options):
12
+ # Use logical version matrix to group by logical endpoint, not physical URL
13
+ matrix = registry.get_logical_version_matrix()
14
+ grouped = defaultdict(dict)
15
+ for endpoint, versions in matrix.items():
16
+ grouped[endpoint] = versions
17
+
18
+ if not grouped:
19
+ self.stdout.write("No endpoints registered.")
20
+ return
21
+
22
+ for endpoint in sorted(grouped):
23
+ self.stdout.write(f"\n{endpoint}:")
24
+ versions = grouped[endpoint]
25
+ for version in sorted(versions, key=lambda v: (v is not None, v)):
26
+ label = "unversioned" if version is None else f"v{version}"
27
+ callback_name = self._get_callback_name(versions[version])
28
+ self.stdout.write(f" {label:12} → {callback_name}")
29
+
30
+ self._warn_gaps(grouped)
31
+
32
+ @staticmethod
33
+ def _get_callback_name(callback):
34
+ """Resolve callback name, handling both functions and class-based views."""
35
+ # Try to get from class-based view metadata first
36
+ if hasattr(callback, "view_class"):
37
+ return callback.view_class.__name__
38
+ # Try to get from ViewSet action callback
39
+ if hasattr(callback, "cls"):
40
+ return callback.cls.__name__
41
+ # Fallback to __name__ attribute
42
+ if hasattr(callback, "__name__"):
43
+ return callback.__name__
44
+ # Final fallback for callable instances
45
+ return callback.__class__.__name__
46
+
47
+ def _warn_gaps(self, grouped):
48
+ for endpoint, versions in grouped.items():
49
+ numeric = sorted(v for v in versions if v is not None)
50
+ if not numeric:
51
+ # Unversioned endpoints don't have gaps
52
+ continue
53
+
54
+ # Only check for gaps within the endpoint's actual span
55
+ min_registered = min(numeric)
56
+ max_registered = max(numeric)
57
+
58
+ for v in range(min_registered, max_registered + 1):
59
+ if v not in versions:
60
+ self.stdout.write(
61
+ self.style.WARNING(f" [{endpoint}] v{v} is not defined.")
62
+ )
@@ -12,6 +12,7 @@ class UrlRegistry:
12
12
 
13
13
  _SOURCE_VERSION_ATTR = "_django_api_versioning_source_version"
14
14
  _ROUTE_VERSION_ATTR = "_django_api_versioning_route_version"
15
+ _LOGICAL_ENDPOINT_ATTR = "_django_api_versioning_logical_endpoint"
15
16
 
16
17
  def __init__(self) -> None:
17
18
  self.urlpatterns: list[URLPattern] = []
@@ -23,6 +24,7 @@ class UrlRegistry:
23
24
  name: str | None = None,
24
25
  source_version: int | None = None,
25
26
  route_version: int | None = None,
27
+ logical_endpoint: str | None = None,
26
28
  ) -> None:
27
29
  """Register a route, preferring definitions from newer source versions."""
28
30
  route_index = self._find_route_index(route)
@@ -36,6 +38,8 @@ class UrlRegistry:
36
38
  pattern = self._create_pattern(route, view, name)
37
39
  setattr(pattern, self._SOURCE_VERSION_ATTR, source_version)
38
40
  setattr(pattern, self._ROUTE_VERSION_ATTR, route_version)
41
+ if logical_endpoint is not None:
42
+ setattr(pattern, self._LOGICAL_ENDPOINT_ATTR, logical_endpoint)
39
43
 
40
44
  if route_index is None:
41
45
  self.urlpatterns.append(pattern)
@@ -58,6 +62,24 @@ class UrlRegistry:
58
62
  matrix.setdefault(route, {})[route_version] = pattern.callback
59
63
  return matrix
60
64
 
65
+ def get_logical_version_matrix(self) -> dict[str, dict[int | None, Callable]]:
66
+ """
67
+ Return ``{logical_endpoint: {route_version: callback}}``.
68
+
69
+ Groups physical URLs by their logical endpoint identity. This is used
70
+ by check_versions to correctly identify gaps within each logical
71
+ endpoint's version span, avoiding false warnings.
72
+ """
73
+ matrix: dict[str, dict[int | None, Callable]] = {}
74
+ for pattern in self.urlpatterns:
75
+ # Use logical endpoint if available, else fall back to route pattern
76
+ logical_id = getattr(
77
+ pattern, self._LOGICAL_ENDPOINT_ATTR, str(pattern.pattern)
78
+ )
79
+ route_version = getattr(pattern, self._ROUTE_VERSION_ATTR, None)
80
+ matrix.setdefault(logical_id, {})[route_version] = pattern.callback
81
+ return matrix
82
+
61
83
  def _find_route_index(self, route: str) -> int | None:
62
84
  """Return the index of a registered route, or None if absent."""
63
85
  for index, pattern in enumerate(self.urlpatterns):
@@ -109,7 +131,37 @@ class UrlRegistry:
109
131
  )
110
132
 
111
133
  if isinstance(view, type) and callable(getattr(view, "as_view", None)):
112
- view = view.as_view()
134
+ # Check if this is a DRF ViewSet (has actions in signature)
135
+ # ViewSets require an action dict to be passed to as_view()
136
+ try:
137
+ import inspect
138
+
139
+ sig = inspect.signature(view.as_view)
140
+ # If as_view has an 'actions' parameter, it's likely a ViewSet
141
+ if "actions" in sig.parameters:
142
+ actions_param = sig.parameters["actions"]
143
+ # If 'actions' has no default, it's required (ViewSet behavior)
144
+ if actions_param.default == inspect.Parameter.empty:
145
+ raise TypeError(
146
+ f"ViewSet '{view.__name__}' cannot be registered directly. "
147
+ f"Pass a configured callable like: "
148
+ f"{view.__name__}.as_view({{'get': 'list', 'post': 'create'}})"
149
+ )
150
+ except Exception:
151
+ # If inspection fails, try calling as_view() anyway
152
+ # to get the original error message if it is indeed a problem
153
+ pass
154
+
155
+ try:
156
+ view = view.as_view()
157
+ except TypeError as e:
158
+ # Re-raise with better context if it's an actions-related error
159
+ if "actions" in str(e):
160
+ raise TypeError(
161
+ "ViewSet requires action configuration. "
162
+ "Use view.as_view({'get': 'list', ...}) with appropriate HTTP methods."
163
+ ) from e
164
+ raise
113
165
  return path(route, view, name=name)
114
166
 
115
167
  def _sort_urlpatterns(self) -> None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: django-api-versioning
3
- Version: 0.3.5
3
+ Version: 0.3.6
4
4
  Summary: API versioning for Django and Django REST Framework (DRF), with decorator-based endpoint registration, automatic URL routing, version-specific views, and forward inheritance for backward-compatible API evolution.
5
5
  Author-email: Mojtaba Arvin <ArvinDevDay@gmail.com>
6
6
  License: MIT
@@ -631,6 +631,47 @@ Prints registered routes, their route versions, and the associated callback name
631
631
 
632
632
  Use it to inspect the routing result after adding or changing endpoint declarations.
633
633
 
634
+ **Output interpretation:**
635
+
636
+ The command groups routes by their *logical endpoint* (the path without versioning), not by physical URL. This means:
637
+
638
+ ```text
639
+ users/:
640
+ v1 → users_list_v1
641
+ v2 → users_list_v2
642
+ v3 → users_list_v2
643
+ v4 → users_list_v2
644
+ ```
645
+
646
+ Even though physical URLs are `/api/v1/users/`, `/api/v2/users/`, etc., the command groups them under the logical endpoint `users`.
647
+
648
+ **Callback name resolution:**
649
+
650
+ The command resolves callback names intelligently:
651
+
652
+ - **Function-based views:** Shows the function name (e.g., `my_view`)
653
+ - **Django View classes:** Shows the class name (e.g., `MyView`)
654
+ - **DRF APIView:** Shows the class name (e.g., `MyAPIView`)
655
+ - **DRF ViewSet actions:** Shows the ViewSet class name (e.g., `MyViewSet`)
656
+
657
+ **Gap detection:**
658
+
659
+ The command warns about missing versions within an endpoint's span:
660
+
661
+ ```text
662
+ users:
663
+ v1 → users_list_v1
664
+ v3 → users_list_v3
665
+ [users] v2 is not defined.
666
+ ```
667
+
668
+ It does NOT warn about versions before an endpoint's introduction or after its final declaration:
669
+
670
+ ```text
671
+ # No warning for v1 (starts at v2)
672
+ # No warning for v4 (ends at v3)
673
+ ```
674
+
634
675
  ### `assert_version_matrix` — guard routing changes in CI
635
676
 
636
677
  The package provides a snapshot utility for detecting unintended changes to the registered route matrix.
@@ -825,7 +866,31 @@ A generic view must implement the HTTP handlers required by its registered route
825
866
 
826
867
  A DRF `ViewSet` class cannot be passed directly to `@endpoint` as a normal class-based view. Its `as_view()` method requires an action mapping, while the package invokes `as_view()` without one.
827
868
 
828
- Use DRF routers for standard ViewSet resource routing.
869
+ To register a ViewSet action, pass a pre-configured callable:
870
+
871
+ ```python
872
+ from rest_framework.viewsets import ViewSet
873
+ from django_api_versioning import endpoint
874
+
875
+
876
+ class MyViewSet(ViewSet):
877
+ def list(self, request):
878
+ return JsonResponse({})
879
+
880
+ def create(self, request):
881
+ return JsonResponse({})
882
+
883
+
884
+ # ✓ Correct: pass a configured callable
885
+ @endpoint("items/", version=1)
886
+ def list_items(request):
887
+ return MyViewSet.as_view({"get": "list"})(request)
888
+
889
+ # ✗ Incorrect: class without action mapping
890
+ # @endpoint("items/", version=1, MyViewSet) # TypeError!
891
+ ```
892
+
893
+ For standard ViewSet resource routing (list, create, retrieve, update, destroy), use DRF routers separately.
829
894
 
830
895
  The package does not automatically generate router-style ViewSet routes.
831
896
 
@@ -839,13 +904,49 @@ It does not:
839
904
  - Select serializers based on a request version.
840
905
  - Replace DRF authentication or permission classes.
841
906
  - Replace DRF routers for ViewSet resource routing.
842
- - Automatically set `request.version`.
907
+ - Automatically set `request.version` (DRF's concern).
843
908
  - Use `API_VERSIONING_CHANNELS` to select routes.
844
909
  - Use `API_EFFECTIVE_VERSION_RESOLVER` for tenant-specific route selection.
845
910
  - Validate response payload compatibility through route-matrix checks.
846
911
 
847
912
  Your application remains responsible for API contract design, serializer selection, authentication, permissions, business logic, and request-level compatibility tests.
848
913
 
914
+ ### Package vs. DRF: Division of responsibilities
915
+
916
+ **Package responsibility: Route selection**
917
+
918
+ The package registers literal URL paths (`/api/v1/endpoint`, `/api/v2/endpoint`) and selects the correct handler based on the URL path.
919
+
920
+ **DRF responsibility: request.version**
921
+
922
+ DRF's versioning classes (like `URLPathVersioning`) populate `request.version` if configured. However, DRF's `URLPathVersioning` uses a URL resolver keyword argument named `version`, which the package does not populate. This means:
923
+
924
+ - The package successfully routes requests to version-specific handlers.
925
+ - `request.version` may be `None` unless you configure a custom versioning class.
926
+
927
+ If you need `request.version` populated, consider implementing a custom DRF versioning class that extracts the version from the URL path or adds a custom resolver keyword argument when registering routes.
928
+
929
+ ### Configuration timing
930
+
931
+ Package settings (`API_MAX_VERSION`, `API_BASE_PATH`, etc.) are validated and loaded at module import time. Using Django's `override_settings` after the package has been imported will NOT affect already-loaded configuration:
932
+
933
+ ```python
934
+ # ✓ Correct: configure before importing views
935
+ os.environ["DJANGO_SETTINGS_MODULE"] = "myapp.settings"
936
+ from django.conf import settings
937
+ settings.API_MAX_VERSION = 5
938
+ from myapp import views # Package uses the configured API_MAX_VERSION
939
+
940
+ # ✗ Incorrect: configure after importing
941
+ from django_api_versioning import api_settings
942
+ from django.test import override_settings
943
+ with override_settings(API_MAX_VERSION=5):
944
+ # This does NOT affect api_settings (already loaded)
945
+ ...
946
+ ```
947
+
948
+ Set all configuration in Django settings before importing modules containing `@endpoint` decorators.
949
+
849
950
  ## Migration from 0.2.0
850
951
 
851
952
  Version 0.3.0 replaced the previous forward/backward inheritance flags model with segment-based registration.
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "django-api-versioning"
7
- version = "0.3.5"
7
+ version = "0.3.6"
8
8
  description = "API versioning for Django and Django REST Framework (DRF), with decorator-based endpoint registration, automatic URL routing, version-specific views, and forward inheritance for backward-compatible API evolution."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"