115

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?

7
  • 10
    They are designed to work together. DRF can build on top of your Django models (and Django authentication etc) - you use it instead of plain Django views in the places where you want API endpoints
    – Anentropic
    Mar 5, 2018 at 11:53
  • @Anentropic So If I build my app entirely in DRF then both the things will be taken care of (The building of app itself along with API thing)
    – Rookie_123
    Mar 5, 2018 at 11:55
  • 1
    try reading the DRF docs, eg the tutorial here django-rest-framework.org/tutorial/1-serialization/… ...it shows how you create a Django model and then DRF serializers based on the model, and then views and then an API based on the model and serializers
    – Anentropic
    Mar 5, 2018 at 11:56
  • 9
    "also do I actually need an API" ...if you don't know whether you need an API you probably don't need an API
    – Anentropic
    Mar 5, 2018 at 11:57
  • 1
    it shows you how the concepts fit together by giving a practical example... you can see the Django parts and the DRF parts and also goes from basic to a bit more advanced. I suggest to actually read it and try and understand what you are reading
    – Anentropic
    Mar 5, 2018 at 12:00

12 Answers 12

55

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 tedious. 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.

1
  • 44
    Your second example is incomplete as MyObjSerializer has to be defined somewhere, so it's not as "easy" as the example suggests (you can't get away without listing model fields etc somewhere). It'd be better to make the point that you can reuse the custom serializer in multiple views though. So DRF helps with re-using code in addition to autogenerating a bunch of endpoints, format options, versioning...
    – C S
    Oct 21, 2019 at 3:17
50

Whether you need an api depends on what you want to do. For example, if you want to access everything in your Django models from a mobile device AND a web-app, you would want to use DRF.

Why? Consider the case that you are developing an iOS app that users can sign into and you want to use Django as your backend. If you also want to have a website that they can use to change around their app's profile information (say, update their email address or upload a picture), you would need a way to share the information in your Django models with both a website and the iOS device. How can this be done? By giving the user the ability to create/read/update/delete data by simply telling it a url to go to. Now, if you want to access information from the model you can do it from multiple devices, since any device can visit a url.

However, if you're just building a simple webapp/webpage and keep it all in one place, you can just use straight Django.

Side note: it's a pretty popular opinion that you should try to separate your frontend from your backend as much as possible. In this case, if you want to use some frontend development framework like React, Angular, or Vue, it's gonna get messy trying to include all those resources in the Django template pages even if you only want a simple web app/web page. In this case, you would use DRF to set up your backend, and just hit the urls from the frontend using a tool like axios. In this scenario, your frontend would likely be hosted on something like Node.

Again, what you decide to use really just depends on what you want out of your app/site and how comfortable you are with each tool.

1
  • 31
    This doesn't really explain why prefer DRF over plain Django. You imply with "By giving the user the ability to create/read/update/delete data by simply telling it a url to go to" that DRF can do it but Django can't, which of course is false. You also suggest Django doesn't let you separate front and backend, also false. I guess my point is you don't really explain how DRF helps with these versus just doing it in plain Django, which was the whole point of the question.
    – C S
    Oct 21, 2019 at 3:04
20

The basic purpose of DRF is to provide APIs. APIs are the touch point in an app. Imagine a project where you have a Django wizard and someone on your team is a JavaScript expert and you want to develop mobile app. The JavaScript expert talks about web elements and threading and the Django expert talks templates and ORM, now what? API is your answer. Let Django wiz give APIs and JSON and let JavaScript wiz do his front end magic. Simplest answer I can think of.

1
  • 2
    This answer doesn't explain why DRF is better since API can be realized in plain django aswell Feb 24, 2022 at 5:42
11

In simple words,

Django: provides features for standard web app

Django Rest Framework: provides features to build standard REST API.

5

Let's sum up,

Django :

Tightly coupled with Django Templates.

Django Rest Framework :

Open for building views of my own choices with REST APIs.

3
  • It is incorrect to say django is tightly coupled with django templates. One can create api backend without using django templates.
    – ABN
    May 6 at 16:59
  • That is where Django REST comes into rescue May 15 at 6:00
  • I have created django api backend without django REST or templates.
    – ABN
    May 16 at 10:42
4
  1. Do you actually need Api? It depends on your requirement and resources. If you only need a web application then django provides everything you require to develop a web application. If you need to develop a mobile application that will communicate with a backend server then you will have to implement Api. If you have remote iot devices that needs to publish its data to your server, you will need Api. If you are good at frontend app development, mobile app development, and iot app development or you have resources to have separate team for frontend, backend, mobile and iot app development then it is good design to separate backend and frontend applications. To achieve this separation, your backend will be api based and your frontend, mobile and iot app will communicate with your backend using your backend api. With this design, any changes in backend will have minimal impact on your other apps.

  2. Will these APIs replace your existing Django models? Ideally it should not but I am not sure if using drf will change your django models. I have not used drf to implement api. But if you just use django to implement your api, it will definitely will not change your models. You just need to define your api urls and api views.

  3. Do you require external packages like drf to implement api endpoint in Django? No. You can easily implement Api endpoints using pure Django framework.

  4. A simple way to implement api using pure Django.

    Define your api url -

    urlpatterns = [   
        path('get_all_user/',UserApiView.as_view(),name='get_all_user'), 
    ]
    

    Define your view

    @method_decorator(csrf_exempt,name='dispatch') 
    class UserApiView(View):
    
        def post(self, request):
            response_data = {}
            json_data = json.loads(request.body)
            response_data['user'] = YourMethodToGetModelData(json_data)
            return JsonResponse(response_data)
    

enter image description here

3

the old school used Jinja2 with html5, css3, but this became inconvenient when Single Page Applications became popular.API helps to provide information more convenient for the frontend programmer. You no longer work with the frontend. The API is convenient when developing as Web applications and when developing applications for the phone.

2
  • 1
    What you have described above is server-side render and client-side render. As mentioned before, plain django can do exactly the same things as DRF Feb 24, 2022 at 5:46
  • Of course Django can, but with DRF it is more comfortable to work and it has a lot of comfortable tools to work with API. Feb 25, 2022 at 8:29
2

Simply saying: with just Django you can create server side rendered websites; and with DRF you can create SPAs with a vuejs or react frontend part.

1
  • 7
    You can do all with Django only. DRF provides reusable classes, so we don't have to do lot of similar/repeated task. Aug 7, 2020 at 12:34
1

Here is a link which might give you some insights on what you are looking for. This explains how a django app can be converted into Django Rest Service, and it also explains what a REST Service actually is

https://opensourceforu.com/2017/11/converting-django-app-rest-api/

1

You can use django to build a complete web application, then what is the need of api?

Let's take a example for suppose at first you build a website for your startup using django. Your site grew popular, and for easier access in Android you thought of building a mobile application. Then are you going to maintain a separate database? Nope, because not only it's difficult to maintain, but migrating the old data is also a headache. So here what django rest framework comes into play. You can set up apis to be used by your Android application, hence have to maintain a single database against multiple apps.

1

My personal opinion is that DRF is more suitable for developing a website For example, maybe in the future you need to use API. It is better to implement your website with this framework from the beginning.

0

Suppose you are building a web application.

In order to complete your app, if you want to code more python / Django code then use Django, to the contrary if you want to code more JavaScript code then use Django restful API.

For web application itself I like using Django ,because it is based on python ,it is much cleaner and shorter than js.

Not the answer you're looking for? Browse other questions tagged or ask your own question.