[Understanding APIs] Function-Based and Class-Based Views
Coursera
- This is a API course is one part of the overall Meta Back-end Developer course
1. Introduction
Django is to server HTTP responses to HTTP requests
Django allows us to
views
that is just a callable that accepts a request and return a response
2. Function-based views (FBVs)
Similar to Django, being simple and intuitive
@api_view
decoratorautomatic handling of request data parsing and response data rendering can be achieved in FBVs
1 2 3 4 5 6
from rest_framework.decorators import api_view from rest_framework.response import Response @api_view(['GET']) def hello_world(request): return Response({"message": "Hello, World!"})
3. Class-based views (CBVs)
It is more suitable for implementing more complex web API logic, enhancing code resuability, and better organizing code structure.
DRF provides base classes (
APIView
andViewSet
) that allow easy handling of various HTTP methods and URL patterns.1 2 3 4 5 6
from rest_framework.views import APIView from rest_framework.response import Response class HelloWorldView(APIView): def get(self, request): return Response({"message": "Hello, World!"})
HelloWorldView
class inherits from theAPIView
classget
method that handles HTTP GET requestsThe CBVs is used in conjunction with DRF’s routing system to automatically call the appropriate method based on the URL pattern.
4. Code Flow
Django’s
URL dispatcher
routes the HTTP requests to theHelloWorldView
. Selected according to the URL patternURL dispatcher
is responsible for connecting all incoming HTTP requests. This is done according to Django’sURLconf
settings, where each URL path is mapped to a specific view function or class.meaning of
routes
-> connecting an HTTP request to the view classDjango's URL dispatcher routes the HTTP request to HelloWorldView
means that the URL dispatcher in Django connects the HTTP request received from the client to a view class called HelloWorldView.At this point, the URL pattern determines which view class the request will be connected to.
as_view()
is a class method that instantiates the class and receives an HttpRequest object to call the appropriate method.Inside the as_view() method, the setup() method and the dispatch() method are called.
The
setup()
method initializes the view, and thedispatch()
method checks the type of HTTP request (GET, POST, etc.) and calls the appropriate handler method.The dispatch() method calls the get() method. This get() method handles the HTTP GET request and returns a Response object.
This Response object is sent to the client as an HTTP response.
If the dispatch() method receives an unknown HTTP method, the http_method_not_allowed() method is called. This method returns a
405 Method Not Allowed
response.
Summary
- In summary, the flow of the code is that an HttpRequest is routed to the HelloWorldView, the as_view() method is called to call the appropriate handler method (get()), and this handler method returns an HttpResponse.