Difference between APIView class and viewsets class?

APIView is the most basic class that you usually override when defining your REST view. You usually define your methods like get, put, delete and others see: http://www.cdrf.co/3.5/rest_framework.views/APIView.html. With APIView you define your view and add it to your urls like so:

# in views.py
class MyAPIView(APIView):
     ... #here you put your logic check methods you can use

# in urls.py
url(r'^posts$', MyAPIView.as_view()), #List of all the posts

Because certain things like getting /post/4, deleting /post/4, getting all posts, updating posts, and creating new posts are so common DRF provides ViewSets.

Before you use ViewSets, let me tell you about Generic Classes. They things very well, but you need to provide the full API end point like I did with my MyAPIView view (again for more info check http://www.cdrf.co/ or http://www.django-rest-framework.org/). So you would have to define your own urls path.

But with ViewSets you create ViewSet that actually merges all the above described operations and also you don't need to define the url path you, instead you use a router that makes paths for you like this:

 # views.py
 class PostViewSet(ViewSet):  # here you subclass ViewSet check methods you can override, you have also ModelViewSet,...


 # urls.py 
 router = routers.DefaultRouter()
 router.register(r'post', PostViewSet, base_name='Post')

The functions you add to the APIView are different than the functions you add to the ViewSet class.

  • APIView: you add functions for the particular HTTP method you want to support on your endpoint. Ex: GET, POST, PUT, PATCH, DELETE

  • ViewSet: you would add functions that represent actions that you'd perform on a typical API. Ex: LIST, CREATE, RETRIEVE, UPDATE


APIView allow us to define functions that match standard HTTP methods like GET, POST, PUT, PATCH, etc.

Viewsets allow us to define functions that match to common API object actions like : LIST, CREATE, RETRIEVE, UPDATE, etc.

Viewsets are also used to write logic to perform standard database operations and to interface with a database back-end. And are usually used for existing database model to manage predefined objects.