DEV Community

Cover image for Building out a Notes App with React and a Django Rest API Part 1
Kenneth Kimani
Kenneth Kimani

Posted on • Updated on

Building out a Notes App with React and a Django Rest API Part 1

Building a modern web application can be a complex and challenging task. However, with the right tools and approach, it can also be an incredibly rewarding experience. In this article, we will be exploring how to build a full-stack application using the popular front-end library, React, and the powerful back-end framework, Django. Our focus will be on creating a simple yet powerful note-taking app that allows you to store, update, and delete your notes.

We will start by setting up the development environment and then delve into building the back-end with Django, covering important topics such as models, views, and URL patterns. Next, we will move on to building the front-end with React, including topics such as components, state management, and integrating with the back-end.

Finally, we will cover the deployment process, discussing how to host the app in a production environment and ensuring security and performance. By the end of this article, you will have a good understanding of how to build a complete React + Django application and have the skills to take your own projects to the next level. So, let's get started on building a feature-rich note-taking app!

So starting off we will start up a Django project but first we have to ensure we are using a virtual environment, virtual environments are a crucial tool for maintaining the stability, compatibility, and reproducibility of your Python projects' we do this by:

  • Assuming you have python installed already(Link) create a new folder where you want to put your project and open it up on your fave editor
  • create a new python environment
  • activate environment

Windows
py -m venv <env-name>
<env-name>\Scripts\activate>

Linux
virtualenv <env-name>
source <env-name>/bin/activate

This will activate my environment and we can now install Django by using pip which is the default package manager for Python, and is used to install and manage packages that can be used in your Python projects:

pip install django

We can then run:

django-admin startproject <project-name>

This will create a Folder with the project name you have given with all the files needed to start off your project courtesy of the Django Framework, move into your new project directory and to to test if everything is working fine run the command to start your server:

python manage.py runserver

runserver
This confirms that your server is up and running

We now move on to creating our API which we will use to make calls from the frontend, The concept of my app is similar to the regular Note App found on most modern phones nowadays that lets you track your notes in a CRUD-ely manner. We will first make a django app for the Api:

Python manage.py startapp <app-name>

Next, open settings.py file and input our project name in the INSTALLED_APPS list so that django can include it to the project

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    '<app-name>.apps.ApiConfig' #add it here
]

Enter fullscreen mode Exit fullscreen mode

Next we can set our URL paths for the main project, URL paths play a crucial role in how Django apps handle requests and display content to users. Open the main project urls.py and set the path as:

from django.contrib import admin
from django.urls import path, include


urlpatterns = [

    path('admin/', admin.site.urls),
    path('<app-name>/', include('<app-name>.urls'))

]

Enter fullscreen mode Exit fullscreen mode

Okay now the next step is to create our Note model based on the concept, In Django, models are used to represent the data that is stored in the app's database. A model defines the structure of the data, including the fields and their types, as well as any relationships to other models:

from django.db import models

# Create your models here.
# This is the model for the notes
class Note(models.Model):
    body = models.TextField(null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

# This is the string representation of the object
    def __str__(self):
        return self.title

Enter fullscreen mode Exit fullscreen mode

Lets install Django rest framework and build out our api, Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. DRF is a third-party package for Django that makes it easy to build, test, and debug RESTful APIs written using the Django framework, in your terminal

pip install djangorestframework

Next, we'll create a serializer for our model, This serializer will handle converting our model instance to and from JSON. Make a serializers.py file in the app folder and put in the following code:

from rest_framework import serializers # Import the serializer class
from .models import Note  # Import the Note model

# Create a serializer class
# This class will convert the Note model into JSON
class NoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Note
        fields = '__all__'



Enter fullscreen mode Exit fullscreen mode

Next, we'll create Api views to handle our CRUD functionality we will use views.py and utils.py(create new file in the app folder), In a Django project, utility functions are often separated into their own module to keep the code organized and reusable, so in the utils.py we can have:

# This is the response that we will return
from rest_framework.response import Response
# This is the model that we will use
from .models import Note
# This is the serializer that we will use
from .serializers import NoteSerializer


# This function will return the notes list
def getNotesList(request):
    notes = Note.objects.all().order_by('-updated')
    serializer = NoteSerializer(notes, many=True)
    return Response(serializer.data)


# This function will return the note detail
def getNoteDetail(request, pk):
    notes = Note.objects.get(id=pk)
    serializer = NoteSerializer(notes, many=False)
    return Response(serializer.data)

# This function will create a note
def createNote(request):
    data = request.data
    note = Note.objects.create(
        body=data['body']
    )
    serializer = NoteSerializer(note, many=False)
    return Response(serializer.data)

# This function will update a note
def updateNote(request, pk):
    data = request.data
    note = Note.objects.get(id=pk)
    serializer = NoteSerializer(instance=note, data=data)

    if serializer.is_valid():
        serializer.save()

    return Response(serializer.data)

# This function will delete a note
def deleteNote(request, pk):
    note = Note.objects.get(id=pk)
    note.delete()
    return Response('Note was deleted!')



Enter fullscreen mode Exit fullscreen mode

Next, we can now add our paths for our api by:

from django.urls import path # This is the path function
from . import views # This is the views file


# This is the list of our routes
urlpatterns = [
    path('', views.getRoutes, name='routes'),
    path('notes/', views.getNotes, name='notes'),
    path('notes/<str:pk>/', views.getNote, name='note')
]

Enter fullscreen mode Exit fullscreen mode

We have now completed the functionality of our API and we can now be able to check it out using the Django Rest Framework that will installed earlier on, We first have to to make our database migrations to notify Django of the model that we have created and any changes that have taken place, then we can startup our server:

Migrations
python manage.py makemigrations
python manage.py migrate

Start server
python manage.py runserver

We expect to see our API up and running as such(remember to use the url path that you named your app):

open-server

Now we can see if our endpoints are working as expected, For the
(Api/Notes) we have:

1.GET that will list all the notes:

getNotes

2.POST that will let you create a new note:

newNote

And for the (Api/Notes/str:pk) we have:

1.GET that will let you get the specific note:

getNote

2.UPDATE that will let you update a specific note:

Update

3.DELETE that will delete the specific note:

Delete

Conclusion

In conclusion, Part 1 of our app-building journey has been a great success! We've learned how to create a basic API using Django and Django Rest Framework, but this is just the beginning. This API, though functional, is still in its earliest stages and needs refining. And for all you tech-savvy readers out there, feel free to star it, clone it, and take a closer look at the source code on my GitHub. This is a great opportunity to not only learn, but also contribute to the project. Now, let's shift our focus to Part 2(coming soon :) ). We'll be making the front-end come to life with React, testing our creation, and launching it into the stratosphere with GCP. Get ready for an exciting journey ahead!

Top comments (2)

Collapse
 
raken_goldberg profile image
Raken Goldberg

Great Article, can't wait for part 2, just starting out programming and this has been nice to follow along on

Collapse
 
ki3ani profile image
Kenneth Kimani

Thank you so much for the support glad it helped you