I am stuck trying to work out how to create a Django REST Framework ViewSet.
The API calls I have inherited look like this:
/api/v1/user/<user_id>/like_count
/api/v1/user/<user_id>/friends/
/api/v1/user/login
/api/v1/user/logout/
In my base urls.py I have the following:
urlpatterns = patterns('',
url(r'^api/v1/', include('api.urls')),
url(r'^$', TemplateView.as_view(template_name='base.html'), name='home'),
url(r'^docs/', include('rest_framework_swagger.urls'))
)
I have an app called api. In the api urls.py I have:
from django.conf.urls import url, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'user', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
In my api/views.py file I want to create a UserViewSet class that handles all the possible variants of the url calls.
First I can't work out if I should use:
class UserViewSet(viewsets.ModelViewSet):
or...
class UserViewSet(APIView):
If I understand it correctly I can cater for the
/api/v1/user/login
/api/v1/user/logout
calls using something like:
class UserViewSet(viewsets.APIView):
def login(self, request, format=None):
...
def logout(self,request, format=None):
But I can't work out how to cater for the other variants that have the <user-id> in the url.
Is there a recommended way to do this?
Some API calls have a trailing '/' and some don't. It is what I have been given (to fit in with an existing mobile app).
EDIT: By the way, I have done the DRF tutorial twice now and still can't see how to do this.
EDIT2: I am really struggling to understand the DRF documentation for this. Can anyone provide some example code that deals with my use case?