user7139313
user7139313

Reputation:

What are the differences between the APIView and ViewSets classes in Django?

What are the differences between the APIView and ViewSets classes?

I am following Django REST framework official documentation. I find it lacking in examples.

Can you explain the above difference with a suitable example?

Upvotes: 54

Views: 38435

Answers (4)

alphiii
alphiii

Reputation: 1645

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 do things very well, but you need to provide the full API endpoint 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 URL paths.

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')

Upvotes: 62

Prateek Gupta
Prateek Gupta

Reputation: 2770

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.

Upvotes: 25

dpacman
dpacman

Reputation: 3899

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

Upvotes: 15

PKG
PKG

Reputation: 71

Viewsets and APIView both allow us to write logic for end point but Viewsets dont define functions which map to HTTP methods instead map to common API object actions

Upvotes: 6

Related Questions