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

      Top 10 Use Cases of Vibe Coding in Large-Scale Node.js Applications

      September 3, 2025

      Cloudsmith launches ML Model Registry to provide a single source of truth for AI models and datasets

      September 3, 2025

      Kong Acquires OpenMeter to Unlock AI and API Monetization for the Agentic Era

      September 3, 2025

      Microsoft Graph CLI to be retired

      September 2, 2025

      ‘Cronos: The New Dawn’ was by far my favorite experience at Gamescom 2025 — Bloober might have cooked an Xbox / PC horror masterpiece

      September 4, 2025

      ASUS built a desktop gaming PC around a mobile CPU — it’s an interesting, if flawed, idea

      September 4, 2025

      Hollow Knight: Silksong arrives on Xbox Game Pass this week — and Xbox’s September 1–7 lineup also packs in the horror. Here’s every new game.

      September 4, 2025

      The Xbox remaster that brought Gears to PlayStation just passed a huge milestone — “ending the console war” and proving the series still has serious pulling power

      September 4, 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

      Magento (Adobe Commerce) or Optimizely Configured Commerce: Which One to Choose

      September 4, 2025
      Recent

      Magento (Adobe Commerce) or Optimizely Configured Commerce: Which One to Choose

      September 4, 2025

      Updates from N|Solid Runtime: The Best Open-Source Node.js RT Just Got Better

      September 3, 2025

      Scale Your Business with AI-Powered Solutions Built for Singapore’s Digital Economy

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

      ‘Cronos: The New Dawn’ was by far my favorite experience at Gamescom 2025 — Bloober might have cooked an Xbox / PC horror masterpiece

      September 4, 2025
      Recent

      ‘Cronos: The New Dawn’ was by far my favorite experience at Gamescom 2025 — Bloober might have cooked an Xbox / PC horror masterpiece

      September 4, 2025

      ASUS built a desktop gaming PC around a mobile CPU — it’s an interesting, if flawed, idea

      September 4, 2025

      Hollow Knight: Silksong arrives on Xbox Game Pass this week — and Xbox’s September 1–7 lineup also packs in the horror. Here’s every new game.

      September 4, 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
    <span class="hljs-built_in">cd</span> 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 = [
        ...
        <span class="hljs-string">'rest_framework'</span>,
        <span class="hljs-string">'api'</span>,
    ]
    
    • 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:

    <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Task</span>(<span class="hljs-params">models.Model</span>):</span>
        title = models.CharField(max_length=<span class="hljs-number">200</span>)
        completed = models.BooleanField(default=<span class="hljs-literal">False</span>)
    
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
            <span class="hljs-keyword">return</span> 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:

    <span class="hljs-keyword">from</span> rest_framework <span class="hljs-keyword">import</span> serializers
    <span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Task
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskSerializer</span>(<span class="hljs-params">serializers.ModelSerializer</span>):</span>
        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
            model = Task
            fields = <span class="hljs-string">'__all__'</span>
    
    • 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:

    <span class="hljs-keyword">from</span> rest_framework <span class="hljs-keyword">import</span> generics
    <span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Task
    <span class="hljs-keyword">from</span> .serializers <span class="hljs-keyword">import</span> TaskSerializer
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskListCreate</span>(<span class="hljs-params">generics.ListCreateAPIView</span>):</span>
        queryset = Task.objects.all()
        serializer_class = TaskSerializer
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskDetail</span>(<span class="hljs-params">generics.RetrieveUpdateDestroyAPIView</span>):</span>
        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:

    <span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
    <span class="hljs-keyword">from</span> .views <span class="hljs-keyword">import</span> TaskListCreate, TaskDetail
    
    urlpatterns = [
        path(<span class="hljs-string">'tasks/'</span>, TaskListCreate.as_view(), name=<span class="hljs-string">'task-list'</span>),
        path(<span class="hljs-string">'tasks/<int:pk>/'</span>, TaskDetail.as_view(), name=<span class="hljs-string">'task-detail'</span>),
    ]
    
    • 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:

    <span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
    <span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, include
    
    urlpatterns = [
        path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
        path(<span class="hljs-string">'api/'</span>, include(<span class="hljs-string">'api.urls'</span>)),
    ]
    

    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:

    <span class="hljs-keyword">from</span> rest_framework.permissions <span class="hljs-keyword">import</span> IsAuthenticated
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskListCreate</span>(<span class="hljs-params">generics.ListCreateAPIView</span>):</span>
        ...
        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:

    <span class="hljs-keyword">from</span> rest_framework.permissions <span class="hljs-keyword">import</span> IsAuthenticated
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskListCreate</span>(<span class="hljs-params">generics.ListCreateAPIView</span>):</span>
        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.

    <span class="hljs-keyword">from</span> rest_framework.permissions <span class="hljs-keyword">import</span> IsAdminUser
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AdminOnlyView</span>(<span class="hljs-params">generics.ListAPIView</span>):</span>
        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.

    <span class="hljs-keyword">from</span> rest_framework.permissions <span class="hljs-keyword">import</span> AllowAny
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PublicSignupView</span>(<span class="hljs-params">generics.CreateAPIView</span>):</span>
        serializer_class = SignupSerializer
        permission_classes = [AllowAny]
    

    4. IsAuthenticatedOrReadOnly

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

    <span class="hljs-keyword">from</span> rest_framework.permissions <span class="hljs-keyword">import</span> IsAuthenticatedOrReadOnly
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ArticleView</span>(<span class="hljs-params">generics.RetrieveUpdateAPIView</span>):</span>
        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

    <span class="hljs-keyword">from</span> rest_framework.permissions <span class="hljs-keyword">import</span> BasePermission
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">IsOwner</span>(<span class="hljs-params">BasePermission</span>):</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">has_object_permission</span>(<span class="hljs-params">self, request, view, obj</span>):</span>
            <span class="hljs-keyword">return</span> obj.owner == request.user
    

    Then use it like this:

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskDetailView</span>(<span class="hljs-params">generics.RetrieveUpdateDestroyAPIView</span>):</span>
        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

    PermissionWho Gets Access?
    AllowAnyEveryone (even logged-out users)
    IsAuthenticatedOnly logged-in users
    IsAdminUserOnly admin/staff users
    IsAuthenticatedOrReadOnlyRead: everyone / Write: only logged-in users
    Custom PermissionsYour 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

    How to Make Bluetooth on Android More Reliable

    September 4, 2025
    Development

    Learn Mandarin Chinese for Beginners – Full HSK 1 Level

    September 4, 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

    SQL-R1: A Reinforcement Learning-based NL2SQL Model that Outperforms Larger Systems in Complex Queries with Transparent and Accurate SQL Generation

    Machine Learning

    8 Best PC Games Under 5 GB To Download Now

    Operating Systems

    Servas is a self-hosted bookmark management tool

    Linux

    CVE-2025-3904 – “Drupal Sportsleague Authentication Bypass”

    Common Vulnerabilities and Exposures (CVEs)

    Highlights

    Linux

    Rilasciato KDE Frameworks 6.16: Miglioramenti nella Gestione della GPU e Nuove Funzionalità

    July 12, 2025

    KDE Frameworks è una raccolta di oltre 70 librerie aggiuntive per Qt, che forniscono funzionalità…

    How To Create Kinetic Image Animations with React-Three-Fiber

    July 9, 2025

    CVE-2024-38824 – Apache HTTP Server File Write

    June 13, 2025

    Meta Releases Llama Prompt Ops: A Python Package that Automatically Optimizes Prompts for Llama Models

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

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