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

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 22, 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 Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

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

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 22, 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

    Development

    GPT-5 is Coming: Revolutionizing Software Testing

    July 22, 2025
    Development

    Win the Accessibility Game: Combining AI with Human Judgment

    July 22, 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

    Amfora is a terminal browser for the Gemini protocol

    Linux

    VideoDubber’s YouTube Copyright Checker

    Web Development

    Is OpenAI’s new ChatGPT-4o image generator the end for graphic designers? — Weekend discussion 💬

    News & Updates

    Osman Abdu Wahabrebi

    Web Development

    Highlights

    News & Updates

    This RDR2 deal feels like highway robbery — grab the “Wild West masterpiece” today before it rides off into the sunset

    July 11, 2025

    Rockstar Games’ Red Dead Redemption is one of the best games ever made, down to…

    CVE-2025-4585 – WordPress IRM Newsroom Stored Cross-Site Scripting Vulnerability

    June 13, 2025

    CVE-2025-4266 – PHPGurukul Notice Board System SQL Injection Vulnerability

    May 5, 2025

    Ubuntu 25.10 Adds New Rust Library to Default Installs

    June 13, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

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