Welcome folks today in this blog post we will be building a django notes crud rest api using mongodb database in browser. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an requirements.txt file inside your project directory. Here inside the requirements.txt we will be installing all the dependencies which are required for this django project.
requirements.txt
1 2 3 4 5 6 7 8 |
asgiref==3.3.4 Django==3.0.5 djangorestframework==3.12.4 djongo==1.3.4 pymongo==3.11.3 pytz==2021.1 sqlparse==0.2.4 typing-extensions==3.7.4.3 |
Now we need to install the dependencies which are present inside the above file by the below command
pip install -r requirements.txt
As you can we are installing the below dependencies for our project as shown below
- Django :-> Web server framework required for application
- Django Rest Framework :-> This is rest framework for django
- djongo :-> Interacting with MongoDB Database
- pymongo :-> library for mongodb crud operations
Creating Django Project
Now we will be creating a brand new django project on the command line as shown below. We need to execute the below commands to create the django project
django-admin startproject notesapp
Here as you can see we are using the django-admin command where we have the option startproject and notesapp is the name of the app
Creating a Brand new App of API
As you know django project comprise of small small apps. Now we will create an app as shown below using this command
django-admin startapp api
This will create the api
folder inside your django project. Now we will see the directory structure of django project
Directory Structure of Django Project
Now we will be including the above created app called api
inside the project level settings.py file as shown below
1 2 3 4 5 6 7 8 9 10 |
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'api', ] |
As you can see we are including the rest framework
library as well and also we are including the api django app as well
Configuring MongoDB Database
Now we will be configuring the mongodb database in this django project. For doing this you need to go to settings.py file inside the django project level and include this below code in databases section
1 2 3 4 5 6 |
DATABASES = { 'default' : { 'ENGINE' : 'djongo', 'NAME' : 'notes_database' } } |
As you can see we are including the engine of the database which is djongo library and also we are also including the name of the mongodb database which is notes_database.
Making the Models for Django App
Now to make the models for the django app. We need to navigate to the models.py inside the api django app as shown below
models.py
1 2 3 4 5 6 |
from django.db import models class Note(models.Model): title = models.CharField(max_length=50) text = models.TextField() def __str__(self): return self.title |
Migrate Models to MongoDB Database
Now we will be doing the actual migraton of the models that we have defined above. After this command all these columns will be automatically inserted in the mongodb database and tables. For doing this migration we need to execute the below command as shown below
python manage.py makemigrations
python manage.py migrate
As you can see the tables are successfully created inside the mongodb database.
Creating the Serializer Class For Models
Now we will be creating the serializer class for the models that we created earlier on. For this we need to create the serializer file inside the django app called api as shown below
As you can see we have created serializers.py
file and here you need to copy paste the below code
serializers.py
1 2 3 4 5 6 |
from rest_framework import serializers from .models import Note class NoteSerializer(serializers.ModelSerializer): class Meta: model = Note fields = ('id', 'title', 'text') |
Making the Views for CRUD Operations
Now guys we will be writing the views for handling this crud operations inside mongodb database. For this you need to go to views.py file inside the django app
views.py
1 2 3 4 5 6 7 8 9 |
from rest_framework import generics from .models import Note from .serializers import NoteSerializer class NoteList(generics.ListCreateAPIView): queryset = Note.objects.all() serializer_class = NoteSerializer class NoteDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Note.objects.all() serializer_class = NoteSerializer |
As you can see we have two different views for our Notes model. First view will return all the Notes which are created. And the next view which will be getting the specific information about the Note by using the id. And inside that view we also have update and delete buttons also to delete and update the Note.
Defining the URLs for Django App Routes
First of all we now need to include the views inside the urls array of django app api. For this you need to navigate to the file present inside the urls.py
which is present inside the api
folder.
1 2 3 4 5 6 |
from django.urls import path from api import views urlpatterns = [ path('', views.NoteList.as_view()), path('<int:pk>/', views.NoteDetail.as_view()) ] |
Now guys we will be defining the urls for our django app routes. For this we need to edit the urls.py file inside the django project directory as shown below. You need to copy paste the below code
1 2 3 4 5 6 |
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), # add this line ] |
As you can see we are adding a new url inside the urlpatterns array. Here we are using the path() method in the first argument we are passing the /api route and then we are including the (‘api.urls’) file
Testing the API in Browser
Now we will be testing the django rest api in browser. For starting the django project we need to execute the below command which is shown below
python manage.py runserver
This will start the django project at port number 8000 inside the browser.
As you can see we have awesome GUI interface provided inside the browser to make the CRUD operations with the mongodb database. As you can see we are making a GET request to the /api
and in the response all the records are returned in the form of array of objects.
We have also have the option to return this in the form of json. If you are using any external frontend app like react,vue and angular to consume this rest api. You can change the option to json as shown below
Creating Records Using Post Request
Now you can also use the below html5 form to create new records or you can pass raw json data. This will make a POST request to the Django REST API.
Doing Update & Delete Operations
Now for doing the update and delete operations for the Django REST API. You will visit the below url
http://localhost:8000/api/1
Where 1 is the ID number who need to provide in the address bar
As you can see it has opened the Note Detail View where we have the option to delete this note using the delete button. And also we have the update html5 form where all the details are populated in input fields. And we have the option to make a PUT Request to update the data of the Note.