{{announcement.body}}
{{announcement.title}}

How to Create a REST API in Django

DZone 's Guide to

How to Create a REST API in Django

There are multiple ways to write an API in Django. We'll look at ModelViewSet for basic CRUD operations and APIView for more custom functionality.

· Web Dev Zone ·
Free Resource

There are multiple ways to write an API in Django, but I don't want you confuse them. I will show you the two best ways to implement APIs, which will cover almost all the scenarios.

Both ways are similar to each other. They are:

  1.  APIView
  2. ModelViewSet

APIView is more generic, while ModelViewSet is specific to a Model's CRUD operations (i.e. ModelViewSet is used to perform List, Create, Read, Update, Delete (CRUD ) operations only.) Whereas with APIView, you can implement not only CRUD operations but also other Non-CRUD functionalities like login, logout, generate invoice, download invoice, change fields of multiple models, etc.

You must be thinking, "with APIView we can implement so much, why to learn ModelViewSet?" Well, you will figure out the reason very soon after implementing them both.

Let's start with APIView first.

Prerequisite

Create a Django project and application using the following steps.

Shell


Install Django Rest Framework

Shell


Now, we are ready with the Django Rest Framework setup. Let's create our first API using APIView.

APIView

With APIView, we can implement Get, Post, Delete, Patch, Put methods. Let's create a Book data model and implement CRUD functionality on it.

Edit the file -  DemoProject > DemoApplication > models.py and create a model. (Django will create a new SQL table in Database.)

Python


Edit the file - DemoProject > DemoApplication > views.py

Python


Edit the file - DemoProject > urls.py

Python


Now, Migrate and run the project.

Shell


Open 127.0.0.1/book/ from your browser.

Voila! Your first API has created. 

Now Imagine, We have 10 data models (tables in database) and we have to create 10 such APIS and also implement CRUD functionality for the same. Isn't that a redundant task?

 To avoid repetitive code, Django has ModelViewSet where you can save 1000 of such lines.

ModelViewSet



Edit the file -  DemoProject > DemoApplication > models.py and create a new data model.

Python


Create a new file  -  DemoProject > DemoApplication > serializers.py

Python


Edit the file -  DemoProject > DemoApplication > views.py

Python


Edit the file - DemoProject > urls.py

Python


Now run the server and open 127.0.0.1/student/ from your browser.

Compare the view class of APIView and ModelViewSet. In ModelViewSet, we saved lots of lines of code. Also, Django itself is implementing the CRUD functionality — fewer chances for us to make mistakes.

Topics:
api, crud, django, django development, python, tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}