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
Resquest
instances, not Django'sHttpRequest
instances, which means you will work withRequest
during 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 withResponse
during the devlopment of the API - Any
APIException
exceptions 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