I'm facing an issue with Django REST Framework where a specific route is not appearing in the API list when I access https://myserver.com/api/. Here's my setup:
url.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'myapi', views.myapiViewSet, basename='myapi')
urlpatterns = [
path('api/', include(router.urls)),
# Other URL patterns
]
views.py
class myapiViewSet(ViewSet):
permission_classes = (MaintenanceCheck,)
throttle_classes = [UserRateThrottle]
When I visit https://myserver.com/api/, I expect to see the myapi endpoint listed, but it doesn't appear so when I can access https://myserver.com/api/myapi/ directly and it doesn't work and it shows me "Not Found\n The requested resource was not found on this server."
I can't figure out why the myapi endpoint doesn't show up in the API list. Any insights or suggestions would be greatly appreciated!
Your viewset is not exposing any views, therefore you're getting 404 Not Found
when accessing an url.
Expose an action, by overriding a default endpoint or add a custom path handler with @action
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
class myapiViewSet(ViewSet):
# ...
def list(self, request):
return Response("/ root path endpoint")
@action(detail=False, methods=['GET'])
def custom(self, request, *args, **kwargs):
return Response("custom/ endpoint")
Or use something like ModelViewSet
and DRF will generate the endpoint for you.
Docs: https://www.django-rest-framework.org/api-guide/viewsets/#viewset-actions
Your router is exposed correctly, however if you want to access that viewset directly at the api/
path, leave the registration path empty:
router = DefaultRouter()
router.register('', views.myapiViewSet, basename='myapi')