Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 39 ยท Views and ViewSets

Class-Based Views with APIView

Build DRF endpoints with the APIView class: one method per HTTP verb, get_object helpers, policy attributes, and when to prefer it over generic views.

Function views with @api_view are great for small endpoints, but a resource with list, create, retrieve, update and delete logic soon wants structure. APIView is DRF's class-based foundation: you write one method per HTTP verb (get, post, put, patch, delete) and DRF dispatches to the right one, wrapping it with the same request, response, authentication, permission and exception machinery you have already used.

Every higher-level tool in this chapter (generic views, viewsets) is built on APIView, so understanding it explains the rest.

Your first APIView

Python A list and detail APIView

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Four ideas are visible here:

  1. Methods are verbs. A get method answers GET; DRF returns 405 Method Not Allowed for any verb you did not define. You never write if request.method == ....
  2. as_view() creates the callable Django's router needs. It builds a fresh view instance for every request, so instance attributes are safe per request but class attributes are shared by all requests.
  3. URL arguments arrive as method arguments (pk), exactly as in function views.
  4. is_valid(raise_exception=True) turns bad input into a 400 without an if branch, as shown in Exception Handling.

Notice the get_object helper. Detail views need to find an object in get, put, patch and delete, and a method on the class avoids repeating the lookup. get_object_or_404(Note, pk=pk) from django.shortcuts does the same in one line.

Policy attributes

An APIView carries the same settings you saw in Project Setup, now as class attributes:

Python
class AdminNoteList(APIView):
    authentication_classes = [SessionAuthentication, TokenAuthentication]
    permission_classes = [IsAdminUser]
    throttle_classes = [UserRateThrottle]
    renderer_classes = [JSONRenderer]
    parser_classes = [JSONParser]
    content_negotiation_class = DefaultContentNegotiation
    versioning_class = None

Each attribute replaces the matching global default for this view only. You can also read self.request, self.args, self.kwargs and self.format_kwarg inside any method.

Python Policies on a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

request.user is an AnonymousUser and request.auth is None when nobody authenticated, while the locked view refuses anonymous callers. The allowed_methods property lists the verbs DRF will accept, derived from the methods you defined plus OPTIONS.

Hooks you can override

APIView exposes small methods that run around your handler. You rarely need them, but they explain how DRF works:

Hook Runs Typical use
initial(request, ...) before the handler runs authentication, permissions, throttles, content negotiation
get_serializer-style helpers your own not built in to APIView; generic views add them
finalize_response(request, response, ...) after the handler sets the renderer and negotiated content type
handle_exception(exc) on error delegates to the exception handler
get_authenticators(), get_permissions(), get_throttles() during initial build the instances from the class lists

Override get_permissions() when the rule depends on the method:

Python
def get_permissions(self):
    if self.request.method in ("GET", "HEAD", "OPTIONS"):
        return [AllowAny()]
    return [IsAuthenticated()]

What APIView does not give you

APIView knows nothing about serializers, querysets or pagination. The detail view above repeated "build a serializer, validate, save" three times, and the list view would need hand-written pagination. That repetition is exactly what generic views and mixins remove. A good rule of thumb:

  • Use APIView for endpoints that are not plain CRUD on a model: a login endpoint, a report, a webhook receiver, a "send me a password reset" action, an aggregate.
  • Use generic views or viewsets for CRUD on models.

Keep views thin. Move business rules (price calculation, state changes) into model methods or a service function, and let the view translate between HTTP and those functions.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does APIView decide which method handles a request?

    DRF dispatches to a lowercase method named after the verb, and returns 405 if there is none.
  2. 2. What does as_view() do?

    Django's URL resolver needs a callable; as_view() builds one that instantiates your class for each request.
  3. 3. Which is the best use for a plain APIView?

    For ordinary CRUD, generic views save code; APIView shines for bespoke endpoints.
  4. 4. How do you require login for just one APIView?

    Class attributes replace the global defaults for that view.

Summary

  • APIView maps HTTP verbs to methods and adds DRF's request handling, policies and error conversion.
  • Use as_view() in URL patterns and read URL arguments as method parameters.
  • Helper methods such as get_object avoid repeating lookups.
  • Policy attributes (permission_classes, renderer_classes, ...) override global settings per view.
  • It has no serializer or queryset support, so CRUD-heavy views should use generics.

Next: Generic Views and Mixins