In the world of web development, the combination of Django Rest Framework and React is a powerful one. DRF is an extension of the Django web framework, which is known for its simplicity, flexibility, and robustness, making it an excellent choice for backend development. On the other hand, React, with its component-based architecture and efficient rendering, is a popular choice for frontend development.
In this blog, we will walk you through the process of integrating a Django Rest Framework backend with a React frontend. To demonstrate this we will be creating a CRUD application where you can manage your watchlist and the streaming services of the shows. In this blog, we will mostly focus on the integration part, for more details the code repositories are attached at the end of this blog.
Related read: Building a Robust CRUD Application with Node.js and MongoDB
DRF provides a high-level, reusable set of tools that simplify API development. This allows developers to create APIs quickly and efficiently, reducing development time and effort. Let’s start setting up the backend.
➡️ Installing Python and Virtual Environment: If you don’t have Python in your system here is the link to download and install Python. During installation, make sure pip is also installed with it. After the installation, let’s move to creating the project. Before that, it is important to use a virtual environment for any Python project to segregate packages from conflicting globally. Here’s the command to create and activate a virtual environment.
> python -m venv env > env\Scripts\activate
➡️ Install Django and Django REST Framework:
> pip install django djangorestframework
➡️ Create a new Django project and navigate into it:
> django-admin startproject backend > cd backend
➡️ Create a new Django app:
python manage.py startapp app
➡️ In the models.py file of the API app, we need to define our models. These are the data structures that Django will use to create the database schema.
➡️ Create a folder API in the app to keep and In the app/api/serializers.py file, define your serializers. These will be used to convert model instances to JSON.
➡️ In the app/api/views.py file, define your views. These will handle HTTP requests and responses.
➡️ Finally, in the app/api/urls.py file, define your URL routes. These will map URLs to views. We will use these URLs (endpoints) to send/receive data to/from the backend. Here is the URL file:
urls.py from django.urls import path from app.api import views urlpatterns = [ path('', views.WatchListAV.as_view(), name="watchlist"), path('<int:pk>/', views.WatchListDetailAV.as_view(), name="watchlist-detail"), path('platform/', views.StreamPlatformAV.as_view(), name='streamplatform-list'), path('platform/<int:pk>/', views.StreamPlatformDetailAV.as_view(), name='streamplatform-detail'), ]
Related read: Test Driven Development Approach using Django Rest Framework
We will use the Create React app, a tool that sets up a modern web app by running one command.
➡️ Install Node.js and npm: Node.js is a JavaScript runtime that allows you to run JavaScript on your server. npm is a package manager for Node.js.
➡️ Create a new React app and navigate into it:
npx create-react-app frontend cd frontend
➡️ In the src directory, create your components. Each component should be in its file and should have a .jsx extension. We will be using @tanstack/react-query to create custom hooks to fetch, create, update, and delete data from the backend. We will also use @tanstack/react-table to create tables that will show data that is fetched from the backend. Let’s install the packages using this command:
yarn add @tanstack/react-query @tanstack/react-table
After installation, you will see that the package.json is updated and the above packages will be present in the dependencies array.
➡️ Let’s understand how the frontend code is structured around a few key components and functionalities. Here’s a brief overview:
➡️ In your Django we need to install a package called django-cors-headers. While installing make sure your virtual environment is active. Here is the command to install.
> pip install django-cors-headers
➡️ After successful installation, we need to make the following changes in the settings.py file.
INSTALLED_APPS = [ ... 'app', 'rest_framework', 'corsheaders' ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', ... ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] } CORS_ALLOWED_ORIGINS = [ 'http://localhost:3000' # i am using 3000 port to run the frontend server ]
➡️ Now we need to create migrations and migrate the database.
> python manage.py makemigrations > python manage.py migrate
Note: We are using the inbuilt SQLite database that comes with Django. If you want to use your custom database, you can update the database settings in settings.py.
➡️ Now we are ready to start our backend server using the following command:
> python manage.py runserver
➡️ In your React app, create a utility file called http.js. It contains the get, post, put and delete API call logic using the global fetch method. The global fetch() method starts the process of fetching a resource from the network (here it is our backend), returning a promise that is fulfilled once the response is available.
➡️ Then we set up the requests files, shows.requests.js and platforms.requests.js inside api/requests. These files help us call the get, post, put and delete utility functions that we wrote in the http.js. Here is the code.
shows.requests.js import http from '../http'; const BASE_URL = '/watch-list/'; export const fetchShows = () => http.get(BASE_URL); export const fetchShow = (id) => http.get(`${BASE_URL}${id}/`); export const createShow = (data) => http.post(BASE_URL, data); export const updateShow = (data, id) => http.put(`${BASE_URL}${id}/`, data); export const removeShow = (id) => http.delete(`${BASE_URL}${id}/`); platforms.requests.js import http from '../http'; const BASE_URL = '/watch-list/platform/'; export const fetchPlatforms = () => http.get(BASE_URL); export const createPlatform = (data) => http.post(BASE_URL, data); export const updatePlatform = (data, id) => http.put(`${BASE_URL}${id}/`, data); export const removePlatform = (id) => http.delete(`${BASE_URL}${id}/`);
➡️ Now we have to set up the queries inside the api/queries folder. We create two files, shows.queries.js and platforms.queries.js. You can refer to the @tanstack/react-query documentation to understand the hooks in more detail.
shows.queries.js import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { createShow, fetchShow, fetchShows, removeShow, updateShow } from '../requests/shows.requests'; export const useFetchShows = () => useQuery( ['shows'], async () => { const res = await fetchShows(); return res; }, ); export const useFetchShow = (id) => useQuery( ['shows'], async () => { const res = await fetchShow(id); return res; }, { enabled: id !== undefined, }, ); export const useCreateShow = () => { const queryClient = useQueryClient(); return useMutation( async data => { const res = await createShow(data); return res; }, { onSuccess: () => queryClient.invalidateQueries(['shows']), }, ); }; export const useUpdateShow = () => { const queryClient = useQueryClient(); return useMutation( async ({ data, id }) => { const res = await updateShow(data, id); return res; }, { onSuccess: () => queryClient.invalidateQueries(['shows']), }, ); }; export const useRemoveShow = () => { const queryClient = useQueryClient(); return useMutation( async id => { const res = await removeShow(id); return res; }, { onSuccess: () => queryClient.invalidateQueries(['shows']), }, ); }; platforms.queries.js import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { createPlatform, fetchPlatforms, removePlatform, updatePlatform } from '../requests/platforms.requests'; export const useFetchPlatforms = () => useQuery( ['platforms'], async () => { const res = await fetchPlatforms(); return res; }, ); export const useCreatePlatforms = () => { const queryClient = useQueryClient(); return useMutation( async data => { const res = await createPlatform(data); return res; }, { onSuccess: () => queryClient.invalidateQueries(['platforms']), }, ); }; export const useUpdatePlatform = () => { const queryClient = useQueryClient(); return useMutation( async ({ data, id }) => { const res = await updatePlatform(data, id); return res; }, { onSuccess: () => queryClient.invalidateQueries(['platforms']), }, ); }; export const useRemovePlatform = () => { const queryClient = useQueryClient(); return useMutation( async id => { const res = await removePlatform(id); return res; }, { onSuccess: () => queryClient.invalidateQueries(['platforms']), }, ); };
➡️ Now we can start the process of calling the APIs in our component. We call the useFetchShow hook and it will call the backend and the response of the get request will be saved inside the shows constant.
const shows = useFetchShows();
➡️ For post, put and delete we need to use the mutateAsync method to get a promise which will resolve on success or throw on an error. This is how we are submitting the form to create or update a show inside the CreateUpdateShowForm.jsx component.
const createShow = useCreateShow(); const updateShow = useUpdateShow(); const handleSubmit = e => { e.preventDefault() const payload = { title, storyline, platforms: availablePlatforms?.map(x => ({ name: x })), active: true } if (data?.id) { updateShow.mutateAsync({ data: payload, id: data?.id}, { onSuccess: () => { closeModal(modalId); } }) } else { createShow.mutateAsync(payload, { onSuccess: () => { closeModal(modalId); setTitle(''); setStoryline(''); setAvailablePlatforms([]) } }); } }
➡️ It’s time to run our frontend application.
> npm run start or > yarn start
Here is the result.
So, here are the repositories. You can take a look and understand the code in greater detail.
In this blog, we’ve explored how to integrate a DRF backend with a React frontend, a powerful combination for modern web development. We’ve set up a Django backend, created a React frontend, and connected the two.
This integration allows us to leverage the simplicity and vast library support of Python for server-side logic, and the efficient, component-based architecture of React for the client-side. We went deep into the integration part but did not discuss enough about the other general stuff.
Remember, the key to successful integration lies in understanding how data flows between the backend and frontend, and ensuring that both sides speak the same language, in this case, JSON.
How to Effectively Hire and Manage a Remote Team of Developers.
Download NowThe Mindbowser team's professionalism consistently impressed me. Their commitment to quality shone through in every aspect of the project. They truly went the extra mile, ensuring they understood our needs perfectly and were always willing to invest the time to...
CTO, New Day Therapeutics
I collaborated with Mindbowser for several years on a complex SaaS platform project. They took over a partially completed project and successfully transformed it into a fully functional and robust platform. Throughout the entire process, the quality of their work...
President, E.B. Carlson
Mindbowser and team are professional, talented and very responsive. They got us through a challenging situation with our IOT product successfully. They will be our go to dev team going forward.
Founder, Cascada
Amazing team to work with. Very responsive and very skilled in both front and backend engineering. Looking forward to our next project together.
Co-Founder, Emerge
The team is great to work with. Very professional, on task, and efficient.
Founder, PeriopMD
I can not express enough how pleased we are with the whole team. From the first call and meeting, they took our vision and ran with it. Communication was easy and everyone was flexible to our schedule. I’m excited to...
Founder, Seeke
Mindbowser has truly been foundational in my journey from concept to design and onto that final launch phase.
CEO, KickSnap
We had very close go live timeline and Mindbowser team got us live a month before.
CEO, BuyNow WorldWide
If you want a team of great developers, I recommend them for the next project.
Founder, Teach Reach
Mindbowser built both iOS and Android apps for Mindworks, that have stood the test of time. 5 years later they still function quite beautifully. Their team always met their objectives and I'm very happy with the end result. Thank you!
Founder, Mindworks
Mindbowser has delivered a much better quality product than our previous tech vendors. Our product is stable and passed Well Architected Framework Review from AWS.
CEO, PurpleAnt
I am happy to share that we got USD 10k in cloud credits courtesy of our friends at Mindbowser. Thank you Pravin and Ayush, this means a lot to us.
CTO, Shortlist
Mindbowser is one of the reasons that our app is successful. These guys have been a great team.
Founder & CEO, MangoMirror
Kudos for all your hard work and diligence on the Telehealth platform project. You made it possible.
CEO, ThriveHealth
Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.
CEO, SMILINGMIND
They were a very responsive team! Extremely easy to communicate and work with!
Founder & CEO, TotTech
We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.
Co-Founder, TEAM8s
Mindbowser was very helpful with explaining the development process and started quickly on the project.
Executive Director of Product Development, Innovation Lab
The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.
Co-Founder, Vesica
Mindbowser is professional, efficient and thorough.
Consultant, XPRIZE
Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.
Founder, S.T.A.R.S of Wellness
Mindbowser was great; they listened to us a lot and helped us hone in on the actual idea of the app. They had put together fantastic wireframes for us.
Co-Founder, Flat Earth
Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.
Founder, Child Life On Call
The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!
CEO, SDOH2Health LLC
Mindbowser was easy to work with and hit the ground running, immediately feeling like part of our team.
CEO, Stealth Startup
Mindbowser was an excellent partner in developing my fitness app. They were patient, attentive, & understood my business needs. The end product exceeded my expectations. Thrilled to share it globally.
Owner, Phalanx
Mindbowser's expertise in tech, process & mobile development made them our choice for our app. The team was dedicated to the process & delivered high-quality features on time. They also gave valuable industry advice. Highly recommend them for app development...
Co-Founder, Fox&Fork