Dev./Django

[Django] APIView vs Viewsets

hotamul 2022. 7. 23. 00:59

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 and Viewsets = 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

  1. The APIView is usually focued around HTTP methods

  2. So 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)

  3. Using the APIView, provide more flexibility of the URL structure and also the logic that's used to process requests.

  4. 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 an APIView.
    The APIView is great for things like authentication, running jobs or making subsequent calls to external APIs.


Viewsets

  1. The Viewsets is focused around actions.
    So the naming of the functions includes things like retrieve, list, update, partial update and destroy.

  2. The Viewsets will map specifically to a model in your system. (Django models)

  3. Use Routers to generate URLs.

  4. Great for CRUD operations on models.