In this gist, I will show the difference between three ways to build endpoints with Django Rest Framework. The pros and cons of each one, when you should use it and so on.
A REST framework provides an APIView class, which subclasses Django's View class.
According to the docs, the View class is a callable which takes a request and returns a response. Is more than the view function because we can wrappe better the request-response flow, following REST principles
# view function
from django.http import HttpResponse
def my_view(request):
if request.method == 'GET':
# code
return HttpResponse('result')
# view class
from django.http import HttpResponse
from django.views import View
class MyView(View):
def get(self, request):
# code
return HttpResponse('result')
The APIView classes are different from regular View clases in the following ways:
- Requests passed to the handler methods will be REST framework's
Resquestinstances, not Django'sHttpRequestinstances, which means you will work withRequestduring the development of the API - Handler methods may return REST framework's
Response, instead of Django'sHttpResponse. The view will manage content negotiation and setting the correct renderer on the response, which means you will work withResponseduring the devlopment of the API - Any
APIExceptionexceptions will be caught and mediated into appropriate responses. - Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method.
We can write either the functions like in Django, but using a decorator @api_view and specificying the allowed methods