Python – Django or Django Rest Framework

djangodjango-rest-frameworkpython

I have made a certain app in Django, and I know that Django Rest Framework is used for building APIs. However, when I started to read about Django Rest Framework on their website, I noticed that each and every thing in API Guide(like request, response, views etc.) claims it is superior to Django (request, response, views etc.).

The thing I am not understanding is whether these APIs will replace my existing Django models, views etc. or how can I use them differently in my existing Django code?

I am quite familiar with Django, but not able to understand exactly what Django Rest Framework is even after spending some time on it. (I know it is used for APIs.) Also, do I actually need an API? My app is able to send data to the server without an API, so in what case would I need an API?

Best Answer

Django Rest Framework makes it easy to use your Django Server as an REST API.

REST stands for "representational state transfer" and API stands for application programming interface.

You can build a restful api using regular Django, but it will be very tidious. DRF makes everything easy. For comparison, here is simple GET-view using just regular Django, and one using Django Rest Framework:

Regular:

from django.core.serializers import serialize
from django.http import HttpResponse


class SerializedListView(View):
    def get(self, request, *args, **kwargs):
        qs = MyObj.objects.all()
        json_data = serialize("json", qs, fields=('my_field', 'my_other_field'))
        return HttpResponse(json_data, content_type='application/json')

And with DRF this becomes:

from rest_framework import generics


class MyObjListCreateAPIView(generics.ListCreateAPIView):
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = MyObjSerializer

Note that with DRF you easily have list and create views as well as authentication.