Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      In-House vs. Outsource Node.js Development Teams: 9 Key Differences for the C-Suite (2025)

      July 19, 2025

      Why Non-Native Content Designers Improve Global UX

      July 18, 2025

      DevOps won’t scale without platform engineering and here’s why your teams are still stuck

      July 18, 2025

      This week in AI dev tools: Slack’s enterprise search, Claude Code’s analytics dashboard, and more (July 18, 2025)

      July 18, 2025

      I ditched my Bluetooth speakers for this slick turntable – and it’s more practical than I thought

      July 19, 2025

      This split keyboard offers deep customization – if you’re willing to go all in

      July 19, 2025

      I spoke with an AI version of myself, thanks to Hume’s free tool – how to try it

      July 19, 2025

      I took a walk with Meta’s new Oakley smart glasses – they beat my Ray-Bans in every way

      July 19, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The details of TC39’s last meeting

      July 19, 2025
      Recent

      The details of TC39’s last meeting

      July 19, 2025

      Simple wrapper for Chrome’s built-in local LLM (Gemini Nano)

      July 19, 2025

      Online Examination System using PHP and MySQL

      July 18, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Top 7 Computer Performance Test Tools Online (Free & Fast)

      July 19, 2025
      Recent

      Top 7 Computer Performance Test Tools Online (Free & Fast)

      July 19, 2025

      10 Best Windows 11 Encryption Software

      July 19, 2025

      Google Chrome Is Testing Dynamic Country Detection for Region-Specific Features

      July 19, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Build a REST API in Django

    How to Build a REST API in Django

    April 16, 2025

    If you’re building a web or mobile app, chances are you’re going to need a way to send and receive data between your app and a server.

    That’s where REST APIs come in. They help apps talk to each other – kind of like a waiter taking your order and bringing your food back. And if you’re using Django, you’re already halfway there.

    Django is one of the most popular web frameworks out there. It’s fast, secure, and packed with useful tools. Combine it with Django REST Framework (DRF), and you’ve got everything you need to build a solid REST API without spending weeks figuring it all out.

    In this guide, I’ll walk you through the whole process of building a REST API in Django from scratch.

    What we’ll cover:

    1. What is a REST API?

    2. Tools You’ll Need

    3. How to Build a REST API in Django

      • Step 1: Set Up Your Django Project

      • Step 2: Create a Model

      • Step 3: Make a Serializer

      • Step 4: Create the Views

      • Step 5: Set Up URLs

      • Step 6: Test It!

    4. DRF Permissions

      • Common Built-In Permissions

      • Custom Permissions

      • Combining Permissions

    5. FAQs

    6. Final Thoughts

    What is a REST API?

    Before we get started, let’s get one thing straight: What’s even is a REST API?

    A REST API (short for “Representational State Transfer”) is a way for two systems – like a website and a server – to talk to each other using standard HTTP methods like GET, POST, PUT, and DELETE.

    Let’s say you have a to-do app. You want to:

    • Get a list of tasks

    • Add a new task

    • Update a task

    • Delete a task

    You can do all of that through a REST API. It’s like setting up your own menu of commands that other apps (or your frontend) can use to work with your data.

    Tools You’ll Need:

    Here’s what you’ll be using in this tutorial:

    • Python (preferably 3.8+)

    • Django (web framework)

    • Django REST Framework (DRF) (to build APIs)

    • Postman or curl (for testing)

    You can install DRF with:

    pip install djangorestframework
    

    How to Build a REST API in Django

    Here is how to get started:

    Step 1: Set Up Your Django Project

    If you haven’t already, start a new Django project:

    django-admin startproject myproject
    cd myproject
    python manage.py startapp api
    
    • django-admin startproject myproject – Creates a new Django project named myproject, which contains configuration files for your whole site.

    • cd myproject – Move into your new project directory.

    • python manage.py startapp api – Creates a new Django app named api where your models, views, and API logic will live.

    Now add 'rest_framework' and 'api' to your INSTALLED_APPS in settings.py:

    INSTALLED_APPS = [
        ...
        'rest_framework',
        'api',
    ]
    
    • rest_framework is the Django REST Framework – it gives you tools to easily create APIs.

    • 'api' tells Django to look in the api folder for models, views, and so on.

    Step 2: Create a Model

    Let’s make a simple model – a task list.

    In api/models.py:

    from django.db import models
    
    class Task(models.Model):
        title = models.CharField(max_length=200)
        completed = models.BooleanField(default=False)
    
        def __str__(self):
            return self.title
    
    • title: A short piece of text (like “Buy groceries”). CharField is used for strings.

    • completed: A Boolean (True or False) to mark if a task is done.

    • __str__: This special method returns a string version of the model when printed – useful for debugging and the admin panel.

    Then run:

    python manage.py makemigrations
    python manage.py migrate
    
    • makemigrations: Prepares the changes to the database schema.

    • migrate: Applies those changes to the actual database.

    Step 3: Make a Serializer

    Serializers turn your Django model into JSON (the data format used in APIs) and back.

    In api/serializers.py:

    from rest_framework import serializers
    from .models import Task
    
    class TaskSerializer(serializers.ModelSerializer):
        class Meta:
            model = Task
            fields = '__all__'
    
    • Serializers convert model instances (like a Task) to and from JSON, so they can be sent over the web.

    • ModelSerializer is a shortcut that automatically handles most things based on your model.

    • fields = '__all__' means include every field in the model (title and completed).

    Step 4: Create the Views

    Here’s where the logic goes. You can use class-based or function-based views. Let’s go with class-based using DRF’s generics.

    In api/views.py:

    from rest_framework import generics
    from .models import Task
    from .serializers import TaskSerializer
    
    class TaskListCreate(generics.ListCreateAPIView):
        queryset = Task.objects.all()
        serializer_class = TaskSerializer
    
    class TaskDetail(generics.RetrieveUpdateDestroyAPIView):
        queryset = Task.objects.all()
        serializer_class = TaskSerializer
    

    These are generic class-based views provided by Django REST Framework to save you time.

    1. TaskListCreate:

      • Handles GET requests to list all tasks.

      • Handles POST requests to create new tasks.

    2. TaskDetail:

      • Handles GET for one task, PUT/PATCH for updating, and DELETE to remove a task

    Step 5: Set Up URLs

    First, make a urls.py file in the api folder (if it doesn’t exist).

    In api/urls.py:

    from django.urls import path
    from .views import TaskListCreate, TaskDetail
    
    urlpatterns = [
        path('tasks/', TaskListCreate.as_view(), name='task-list'),
        path('tasks/<int:pk>/', TaskDetail.as_view(), name='task-detail'),
    ]
    
    • tasks/: The route to access or create tasks.

    • tasks/<int:pk>/: The route to get, update, or delete a single task by its primary key (pk).

    Then, in your main myproject/urls.py:

    Now, hook this into the main urls.py in your project folder:

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('api/', include('api.urls')),
    ]
    

    Step 6: Test It!

    Start the server:

    python manage.py runserver
    

    Open Postman or curl and try hitting these endpoints:

    • GET /api/tasks/ – get all tasks

    • POST /api/tasks/ – create a new task

    • GET /api/tasks/1/ – get a specific task

    • PUT /api/tasks/1/ – update a task

    • DELETE /api/tasks/1/ – delete a task

    And that’s it – you’ve got a working REST API.

    This setup gives you a fully functional REST API with just a few lines of code, thanks to Django REST Framework. You should now understand:

    • How models define your database structure

    • How serializers turn models into JSON and vice versa

    • How views control API behaviour (get, post, update, delete)

    • How URL routing connects your views to web requests

    DRF Permissions

    Right now, anyone can use your API. But what if you only want certain users to have access?

    DRF gives you simple ways to handle this. For example, to make an API only available to logged-in users:

    from rest_framework.permissions import IsAuthenticated
    
    class TaskListCreate(generics.ListCreateAPIView):
        ...
        permission_classes = [IsAuthenticated]
    

    There are more permissions you can use, like IsAdminUser custom permissions, for example.

    Let’s break this down and go deeper into permissions in Django REST Framework (DRF), including:

    What are Permissions in DRF?

    Permissions in DRF control who can access your API and what actions they can perform (read, write, delete, etc.).

    They’re applied per view (or viewset), and they’re checked after authentication, meaning they build on top of checking whether the user is logged in.

    Common Built-In Permissions

    DRF gives you a few super useful built-in permission classes out of the box:

    1. IsAuthenticated

    This one ensures that only logged-in users can access the view:

    from rest_framework.permissions import IsAuthenticated
    
    class TaskListCreate(generics.ListCreateAPIView):
        queryset = Task.objects.all()
        serializer_class = TaskSerializer
        permission_classes = [IsAuthenticated]
    

    Only users who have been authenticated (for example, via session login or token) will be able to list or create tasks. Anyone else gets a 403 Forbidden response.

    2. IsAdminUser

    Only allows access if user.is_staff is True.

    from rest_framework.permissions import IsAdminUser
    
    class AdminOnlyView(generics.ListAPIView):
        queryset = User.objects.all()
        serializer_class = UserSerializer
        permission_classes = [IsAdminUser]
    

    Only admin users (usually set via Django admin or superuser status) can access this view.

    3. AllowAny

    Allows all users, even unauthenticated ones. This is the default for open APIS like sign-up pages.

    from rest_framework.permissions import AllowAny
    
    class PublicSignupView(generics.CreateAPIView):
        serializer_class = SignupSerializer
        permission_classes = [AllowAny]
    

    4. IsAuthenticatedOrReadOnly

    Authenticated users can read and write, unauthenticated users can only read (GET, HEAD, OPTIONS).

    from rest_framework.permissions import IsAuthenticatedOrReadOnly
    
    class ArticleView(generics.RetrieveUpdateAPIView):
        queryset = Article.objects.all()
        serializer_class = ArticleSerializer
        permission_classes = [IsAuthenticatedOrReadOnly]
    

    Use case: Great for blogs or article APIS where the public can read but only registered users can write/update.

    Custom Permissions

    Want more control? You can create your permissions by subclassing BasePermission.

    Example: Only allow owners of an object to edit it

    from rest_framework.permissions import BasePermission
    
    class IsOwner(BasePermission):
        def has_object_permission(self, request, view, obj):
            return obj.owner == request.user
    

    Then use it like this:

    class TaskDetailView(generics.RetrieveUpdateDestroyAPIView):
        queryset = Task.objects.all()
        serializer_class = TaskSerializer
        permission_classes = [IsAuthenticated, IsOwner]
    
    • First, a user must be logged in (IsAuthenticated).

    • Then, only the owner of that specific Task can view, update, or delete it.

    Combining Permissions

    You can combine multiple permission classes, and all must return True for access to be granted.

    permission_classes = [IsAuthenticated, IsAdminUser]
    

    This means: user must be both authenticated and an admin.

    TL;DR

    Permission Who Gets Access?
    AllowAny Everyone (even logged-out users)
    IsAuthenticated Only logged-in users
    IsAdminUser Only admin/staff users
    IsAuthenticatedOrReadOnly Read: everyone / Write: only logged-in users
    Custom Permissions Your rules (e.g., only owners)

    FAQs

    Do I need Django REST Framework to build an API in Django?

    Technically, no – but DRF makes your life much easier. Without DRF, you’d have to manually handle things like:

    • Parsing and validating JSON requests

    • Writing views to serialise Python objects to JSON

    • Managing HTTP status codes and responses

    • Handling authentication and permissions on your own

    In short, you’d be reinventing the wheel – but DRF does all of this for you with far less code.

    Can I use this API with a React or Vue frontend?

    Absolutely. Your Django API will send and receive data in JSON format — which is exactly what modern frontend frameworks like React and Vue are designed to work with. Just make sure you handle CORS (Cross-Origin Resource Sharing) correctly.

    How do I make my API faster?

    You can:

    • Use caching to store frequent responses

    • Enable pagination to reduce data load

    • Explore async views (Django 3.1+ supports async) for faster I/O
      DRF also offers built-in tools for pagination, throttling, and more performance tweaks out of the box.

    Final Thoughts

    Building a REST API in Django might sound like a big job, but it’s just a series of small, manageable steps.

    Once you’ve done it once, it gets way easier the next time. Plus, using Django REST Framework saves a ton of time—you’re not reinventing the wheel every time.

    Further Resources

    Want to keep learning? Here are a few solid places to dig deeper:

    • Official Django REST Framework Docs

    • Django’s Official Docs

    • Simple JWT for token authentication

    • Test your API with Postman

    • Real Python’s Django API Guide

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleNeed to relax? This new iPhone feature does the trick for me – here’s how
    Next Article How to Build RAG AI Agents with TypeScript

    Related Posts

    Artificial Intelligence

    Scaling Up Reinforcement Learning for Traffic Smoothing: A 100-AV Highway Deployment

    July 19, 2025
    Repurposing Protein Folding Models for Generation with Latent Diffusion
    Artificial Intelligence

    Repurposing Protein Folding Models for Generation with Latent Diffusion

    July 19, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-45042 – Tenda AC9 Command Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    How to open Control Center on your iPhone without swiping from top: 4 easier ways

    News & Updates

    Aesthetics over upgrades

    Web Development

    My favorite bike computer just got more affordable but with just as many safety features

    News & Updates

    Highlights

    C++ Setup and Installation Tools – CMake, vcpkg, Docker & Copilot Development

    C++ Setup and Installation Tools – CMake, vcpkg, Docker & Copilot

    April 8, 2025

    Setting up a C++ development environment can be one of the most challenging aspects for…

    Bloom Paris TV: Where Refined Art Direction Meets World-Class Production

    July 8, 2025

    Wyze’s new Bulb Cam turns any light socket into a 2K camera – for just $50

    June 3, 2025

    USB Cable Types Guide: Explained for All Users

    July 9, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.