[Answered ]-DRF: API root view doesn't list my APIs for some reasons

1đź‘Ť

DefaultRouter needs to run reverse(viewname) on your views to generate urls for the default view. It won’t know about your dynamic parameter endpoint when it runs.

If it’s acceptable to change your url structure to {endpoint}/access/... and {endpoint}/check/... you can:

router.register(r"access", AccessViewSet, basename="access")
router.register(r"check", CheckViewSet, basename="check")


urlpatterns = [
    re_path(r"(?P<endpoint>.+)/", include(router.urls)),
]

After which, each {endpoint}/ view should have a working default API view.

If you need to preserve your url structure, you’ll have to manually generate a list of available routes like this:

from collections import OrderedDict

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.reverse import reverse

class ApiRoot(APIView):
    """My API root view"""

    def get(self, request, format=None):
        """List of available API endpoints"""

        api_methods = [
            "access-list",
            "check-list",
        ]

        endpoints = [
            "endpoint-a",
            "endpoint-b",
        ]

        routes = OrderedDict()
        for endpoint in endpoints:
            for method in api_methods:
                routes[endpoint + method] = reverse(
                    method, endpoint=endpoint, request=request, format=format
                )

        return Response(routes)

Notice the endpoint=endpoint in the reverse call.

If the code above doesn’t help, please, expand your question with more details of what you’re trying to archive in the first place. I have a feeling you might want to replace your viewsets with an EndpointViewSet with custom ViewSet actions for check and access.

Finally, if you’re looking for routes like {endpoint_id}/access/{access_id}/... and {endpoint_id}/check/{check_id}/... check out drf-nested-routers – a drop-in replacement for DRF’s Routers that supports nesting.

👤Igonato

Leave a comment