Loading Kaushal Patel
All articles

How to Set Up Django REST Framework with React — Step by Step (Full-Stack Guide)

Django REST Framework + React — full-stack, step-by-step guide

Django is brilliant at data, admin and business logic. React is brilliant at fast, interactive interfaces. Put them together — Django with Django REST Framework as the API, React as the front end — and you get one of the most popular full-stack setups there is.

In this guide we’ll build a small Tasks app from scratch: a REST API you can create, list, update and delete tasks with, and a React interface that uses it. Every command is included, and we’ll commit to Git as we go.

Diagram: React on localhost:5173 talks HTTP and JSON to Django REST Framework on 127.0.0.1:8000, which uses the ORM to reach SQLite or Postgres
Two apps that talk in JSON: React in the browser, Django REST Framework on the server.

What you’ll need

Step 1 — Create the project folder and Git repository

We’ll keep both apps in one repository: backend/ for Django and frontend/ for React.

mkdir fullstack-app && cd fullstack-app
git init

Create a .gitignore in this folder so virtual environments, installed packages, build output and secrets never reach Git:

# Python
backend/.venv/
__pycache__/
*.pyc
backend/db.sqlite3

# Node
frontend/node_modules/
frontend/dist/

# Secrets and local settings
.env
Folder tree: fullstack-app with backend (manage.py, config, tasks app with models, serializers, views) and frontend (package.json, .env, src/api.js, src/App.jsx)
Where we’re heading: one repository, two apps.

Step 2 — Set up Django and Django REST Framework

mkdir backend && cd backend
python3 -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\activate

pip install "django~=5.2" djangorestframework django-cors-headers
django-admin startproject config .
python manage.py startapp tasks

That gives you a config package (settings and URLs) and a tasks app. Register the apps in config/settings.py:

INSTALLED_APPS = [
    # …Django's built-in apps…
    "rest_framework",
    "corsheaders",
    "tasks",
]

Step 3 — Create the Task model

In tasks/models.py:

from django.db import models


class Task(models.Model):
    title = models.CharField(max_length=200)
    done = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return self.title

Show it in Django’s admin too — tasks/admin.py:

from django.contrib import admin

from .models import Task

admin.site.register(Task)

Create the database table and an admin user:

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

Step 4 — Build the API: serializer, ViewSet and router

A serializer turns Task objects into JSON and validates incoming JSON. Create tasks/serializers.py:

from rest_framework import serializers

from .models import Task


class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ["id", "title", "done", "created_at"]
        read_only_fields = ["id", "created_at"]

A ViewSet gives you list, create, retrieve, update and delete in a few lines. In tasks/views.py:

from rest_framework import viewsets

from .models import Task
from .serializers import TaskSerializer


class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

A router creates the URLs. Replace config/urls.py with:

from django.contrib import admin
from django.urls import include, path
from rest_framework.routers import DefaultRouter

from tasks.views import TaskViewSet

router = DefaultRouter()
router.register("tasks", TaskViewSet)

urlpatterns = [
    path("admin/", admin.site.urls),
    path("api/", include(router.urls)),
]

That’s a complete REST API:

MethodURLWhat it does
GET/api/tasks/List all tasks
POST/api/tasks/Create a task
GET/api/tasks/1/Get one task
PATCH/api/tasks/1/Update part of a task
DELETE/api/tasks/1/Delete a task

Step 5 — Allow the React app to call the API (CORS)

During development React runs on localhost:5173 and Django on 127.0.0.1:8000. Browsers block requests between different origins unless the server allows them — that’s what django-cors-headers is for. In config/settings.py, add its middleware near the top (before CommonMiddleware) and list the React address:

MIDDLEWARE = [
    "corsheaders.middleware.CorsMiddleware",  # ← as high as possible
    "django.middleware.security.SecurityMiddleware",
    # …the rest stay as they are
]

CORS_ALLOWED_ORIGINS = [
    "http://localhost:5173",
    "http://127.0.0.1:5173",
]

Step 6 — Test the API

python manage.py runserver

Open http://127.0.0.1:8000/api/tasks/. DRF’s browsable API shows an empty list and a form to add tasks right in the browser. Or test from a second terminal:

curl -X POST http://127.0.0.1:8000/api/tasks/ \
  -H "Content-Type: application/json" \
  -d '{"title": "Ship the API"}'

curl http://127.0.0.1:8000/api/tasks/

Save the dependencies and commit the backend (run these from the backend/ folder):

pip freeze > requirements.txt
git add .
git commit -m "Add Django REST API for tasks"

Step 7 — Create the React app with Vite

Leave Django running. In a second terminal, go back to the fullstack-app folder and create the front end:

npm create vite@latest frontend -- --template react
cd frontend
npm install
npm run dev

Open http://localhost:5173 to see the Vite + React starter. Now tell React where the API lives — create frontend/.env:

VITE_API_URL=http://127.0.0.1:8000/api

Step 8 — Talk to the API from React

Keep all API calls in one place. Create frontend/src/api.js:

const API_URL = import.meta.env.VITE_API_URL;

async function request(path, options = {}) {
  const res = await fetch(`${API_URL}${path}`, {
    headers: { "Content-Type": "application/json" },
    ...options,
  });
  if (!res.ok) throw new Error(`API error ${res.status}`);
  return res.status === 204 ? null : res.json();
}

export const getTasks = () => request("/tasks/");

export const createTask = (title) =>
  request("/tasks/", { method: "POST", body: JSON.stringify({ title }) });

export const updateTask = (id, data) =>
  request(`/tasks/${id}/`, { method: "PATCH", body: JSON.stringify(data) });

export const deleteTask = (id) => request(`/tasks/${id}/`, { method: "DELETE" });

Then replace frontend/src/App.jsx with the Tasks interface:

import { useEffect, useState } from "react";
import { createTask, deleteTask, getTasks, updateTask } from "./api";

export default function App() {
  const [tasks, setTasks] = useState([]);
  const [title, setTitle] = useState("");
  const [error, setError] = useState("");

  useEffect(() => {
    getTasks()
      .then(setTasks)
      .catch(() => setError("Couldn't reach the API. Is Django running?"));
  }, []);

  async function handleAdd(event) {
    event.preventDefault();
    if (!title.trim()) return;
    const task = await createTask(title.trim());
    setTasks((current) => [task, ...current]);
    setTitle("");
  }

  async function handleToggle(task) {
    const updated = await updateTask(task.id, { done: !task.done });
    setTasks((current) => current.map((t) => (t.id === updated.id ? updated : t)));
  }

  async function handleDelete(id) {
    await deleteTask(id);
    setTasks((current) => current.filter((t) => t.id !== id));
  }

  return (
    <main style={{ maxWidth: 480, margin: "48px auto", fontFamily: "system-ui" }}>
      <h1>My tasks</h1>
      {error && <p style={{ color: "crimson" }}>{error}</p>}

      <form onSubmit={handleAdd}>
        <input
          value={title}
          onChange={(event) => setTitle(event.target.value)}
          placeholder="Add a task…"
        />
        <button type="submit">Add</button>
      </form>

      <ul>
        {tasks.map((task) => (
          <li key={task.id}>
            <label>
              <input
                type="checkbox"
                checked={task.done}
                onChange={() => handleToggle(task)}
              />{" "}
              {task.title}
            </label>{" "}
            <button onClick={() => handleDelete(task.id)} aria-label={`Delete ${task.title}`}>
              ✕
            </button>
          </li>
        ))}
      </ul>
    </main>
  );
}

Save, and the page at localhost:5173 reloads by itself. Add a few tasks, tick them off, delete one — then refresh the page and open /admin/ on the Django side: everything is stored in the database.

Five steps: React submits the form, fetch POSTs JSON, the DRF serializer validates, the Django model saves, a 201 Created JSON response updates React state
What happens when you click Add: from the React form to the database and back.

Step 9 — Commit and push to GitHub

Vite doesn’t create its own Git repository, so the front end belongs to the one we made in Step 1. From the fullstack-app folder:

cd ..
git add .
git commit -m "Add React front end for tasks"

Create an empty repository on GitHub (no README), then connect and push:

git remote add origin https://github.com/your-username/fullstack-app.git
git branch -M main
git push -u origin main

For the next feature, work on a branch so main always works:

git switch -c feature/due-dates
# …make your changes…
git add .
git commit -m "Add due dates to tasks"
git push -u origin feature/due-dates

Step 10 — Get it ready for production

In production the two apps usually live on separate addresses, for example app.your-domain.com for React and api.your-domain.com for Django.

Where to go next

Troubleshooting

Your checklist

You now have the classic modern stack running end to end: Django and Django REST Framework serving a clean JSON API, and React turning it into a fast interface. Building something on this stack and want a second pair of eyes? Get in touch.

Kaushal Patel

Entrepreneur · Business Owner · IT Consultant — writing about startups, AI and building products.

Keep reading

Related articles