Django REST API – CRUD with DRF
Django REST Framework is used to create web APIs very easily and efficiently. This is a wrapper around over the Django Framework. There are three stages before creating an API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.
In this tutorial, we will discuss CRUD Operations using Django REST API. It assumes you are familiar with Django basics – Django tutorial.
What we are going to build?
For this tutorial, we will be building simple REST APIs for supermarket application. This store contains a variety of food, beverages, and household products, organized into various categories. These categories have subcategories and subcategories have items under them. Each item has a price for which it can be sold. Now we should be able to add, update, view, and delete such records from our database using DRF APIs.
Let’s assume you have Django set up and installed in your system. In case you don’t have any set up at all then refer to the below articles –
- Django Introduction and Installation
- How to Create a Basic Project using MVT in Django ?
- How to Create an App in Django ?
How to install Django REST Framework?
To install Django REST Framework on Windows, Linux or any operating system, one would need pip package. To check how to install pip on your operating system, check out – PIP Installation – Windows || Linux.
Now, run a simple command,
pip install djangorestframework
After installing the REST framework, go to settings.py, and in INSTALLED_APPS add ‘rest_framework’ at the bottom.
For more information refer to our article Django REST Framework Installation.
After installing the DRF and adding it to settings.py, let’s create an app using the command –
python manage.py startapp api
A folder with the name api would have been registered by now.
Let’s add this app to INSTALLED_APPS and urls.py also.
Now, add api urls in urls.py. In GFG_REST.urls.py,
Now let’s create urls.py in our api folder –
Now let’s create our model. We will create an item model. This model will be used by API to perform the CRUD operations.
Now after our app gets ready let’s create the serializer for our Item class.
For this tutorial, we will use the ModelSerializer. If you want to know more about creating serializers manually then refer to the below articles –
- Serializers – Django REST Framework
- HyperlinkedModelSerializer in serializers – Django REST Framework
ModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. It provides a shortcut that lets you automatically create a Serializer class with fields that correspond to the Model fields. The ModelSerializer class is the same as a regular Serializer class, except that:
- It will automatically generate a set of fields for you, based on the model.
- It will automatically generate validators for the serializer, such as unique_together validators.
- It includes simple default implementations of .create() and .update().
Now let’s create our serlializers.py file in the api folder and add the below code –
Creating the View
To render data into frontend, and handle requests from user, we need to create a view. In Django REST Framework, we call these viewsets, so let’s create a view in apis/views.py,
In the above code, the api_view decorator takes a list of HTTP methods that a views should response to. Other methods will response with the Method Not Allowed.
Now let’s update our api/urls.py file –
Now let’s un our server. Run the following commands –
python manage.py makemigrations python manage.py migrate python manage.py runserver
Now head to http://127.0.0.1:8000/api/
Now let’s implement our CRUD Operations through our API.
Django Rest Framework – Create View
Now our create view will use the POST method for inserting data into our database. Let’s create our add_items function in the views.py file.
Now let’s update our urls.py file and add the endpoint for the create view function we just created.
Django Rest Framework – List View
Now our list view will use the GET method for retrieving data from our database. Let’s create our view_items function in the views.py file. This view_items function will either show all the data or filtered data queried by the user according to the category, subcategory, or name.
Now visit http://127.0.0.1:8000/api/all/
This view function also lets us filter by category or subcategory. You can use either of the following URLs i.e. http://127.0.0.1:8000/api/?category=category_name or http://127.0.0.1:8000/api/?subcategory=category_name to filter for both category and subcategory respectively. You can also use http://127.0.0.1:8000/api/all/?name=item_name to search for a specific item.
If we visit http://127.0.0.1:8000/api/all/?category=food our search result will narrow down to –
Django Rest Framework – Update View
Now for our update view function we will use the POST method. Let’s create our update_items function in the views.py file. This view function will update a particular item from the database. It will filter the item with the help of the primary key.
Now head to http://127.0.0.1:8000/api/all/?name=potato
Django Rest Framework – Delete View
For our delete view function we will use the DELETE method. Let’s create our delete_items function in the views.py file. This view function will delete a particular item from the database.
Now visit http://127.0.0.1:8000/api/item/pk/delete/. See the below GIF for better understanding.