[Django] APIView vs Viewsets
What is a view?
- Handles a request made to a URL
- Django uses functions (accepts a request argument and that can be used as your view for handling)
- DRF(Django Rest Framework) uses classes (gives you a bunch of functionality that you can reuse from the DRF)
- Reusable
- Override behavior
- DRF also supports decorators
APIView
andViewsets
= DRF base classes
The APIView
and Viewsets
are base classes provided by DRF that allow you to pull in functionality from the DRF to create APIs.
APIView
The
APIView
is usually focued around HTTP methodsSo when you're using
APIView
, there's specific class method available for all of the different HTTP methods that you want to support on that endpoint. (GET, POST, PUT, PATCH, DELETE)Using the
APIView
, provide more flexibility of the URL structure and also the logic that's used to process requests.The best thing to use
APIView
is useful for non CRUD APIs.
If you creating an API that doesn't map to this functionality (CRUD), then you might want to use anAPIView
.
TheAPIView
is great for things like authentication, running jobs or making subsequent calls to external APIs.
Viewsets
The
Viewsets
is focused around actions.
So the naming of the functions includes things like retrieve, list, update, partial update and destroy.The
Viewsets
will map specifically to a model in your system. (Django models)Use Routers to generate URLs.
Great for CRUD operations on models.