Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@luchiago
Created July 25, 2020 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luchiago/16e0422a3d5a0bab9daff0b67f0a5f85 to your computer and use it in GitHub Desktop.
Save luchiago/16e0422a3d5a0bab9daff0b67f0a5f85 to your computer and use it in GitHub Desktop.
DRF Views

DRF Endpoints, how to build it

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.

Class-based Views

A REST framework provides an APIView class, which subclasses Django's View class.

What's the 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')

What's is the difference between the regular Django's View Class

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's HttpRequest instances, which means you will work with Request during the development of the API
  • Handler methods may return REST framework's Response, instead of Django's HttpResponse. The view will manage content negotiation and setting the correct renderer on the response, which means you will work with Response 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.

The Function Based Views in DRF

We can write either the functions like in Django, but using a decorator @api_view and specificying the allowed methods

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment