3 horizontal lines, burger
3 horizontal lines, burger
3 horizontal lines, burger
3 horizontal lines, burger

3 horizontal lines, burger
Remove all
LOADING ...

Content



    Basic RESTful API Implementation in Django

    Clock
    24.02.2025
    /
    Clock
    08.04.2026
    /
    Clock
    4 minutes
    An eye
    1026
    Hearts
    1
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0

    Introduction

    Good day. Today I'll show you how to create an API for your website and how this API can be used from the client side. I'm writing the backend in Django, and the Django REST framework will handle the creation and configuration of the API. The frontend will be written in Axios.
    Working with an API always involves sending requests to the server and processing the responses. Whether it's sent by Axios, HTMx, or fetch, or processed by something like ReactJS, isn't that important.
    I will demonstrate the process of connecting the REST API using the example of a regular Preset model in a Backend application.

    The process of implementing a REST API on a website

    The process of creating or implementing a Django REST API for a website can be described in the following steps:
    1. You need to create or have an existing Django project
    2. Configure and install the necessary packages
    3. Create the models you want to use on the client-side
    4. Create serializers for them.
    5. Create views (handlers) for them
    6. Connect routes and paths
    7. Write and configure the website's frontend to work with the API
    Let's take everything in order, so let's start with configuring and installing the necessary packages.

    Installing the required packages and setting up the project

    You need to install and enable the following Python modules:
    1. django-cors-headers: to enable Cross-Origin Resource Sharing (CORS) for communication between the React application and the Django API.
    2. djangorestframework: this is a Django application that allows us to easily build an API for our website.
    3. django: our website's backend, database management.
    Now, we enable the newly installed modules in settings.py:
    INSTALLED_APPS = [ ... # Django REST framework 'corsheaders', 'rest_framework', ... ] MIDDLEWARE = [ ... 'django.middleware.csrf.CsrfViewMiddleware', # REST framework 'corsheaders.middleware.CorsMiddleware', ... ]

    Creating Models

    The next step is to decide which models we want to work with. Here's the full code for the model we'll use for serialization. In your application's models.py file, create the model:
    class Preset(models.Model): name = models.CharField(max_length=120) user = models.ForeignKey(get_user_model(), null=True, on_delete=models.CASCADE) timeCreated = models.DateTimeField(auto_now=True, auto_created=True) queries = models.ManyToManyField(Query) def __str__(self): return self.name
    This is just an example and you are free to create your own model with your own fields and methods.

    Creating serializer classes

    After creating the necessary models, we'll need serializers. To do this, import the serializers module from rest_framework and specify the fields we want to serialize. Create a serializers.py file in your application and add the following:
    from rest_framework import serializers from .models import Preset class PresetSerializer(serializers.ModelSerializer): class Meta: model = Preset fields = ('id', 'name', 'user', 'queries')
    A Django serializer is a class or method in Python that converts complex data structures or models into a sequence of bytes or a string (JSON, XML, YAML) or other format suitable for saving to a file, database, or transmission over a network.
    There's nothing special about these serializers. We create a class using inheritance. Then we select the model and fields we want to serialize. We move on to the views.

    Creating views for serializers

    Now, we need to see what we're adding, removing, or changing. We need to create views in the views.py file:
    from rest_framework import viewsets from .serializers import PresetSerializer from .models import Preset class PresetModelView(viewsets.ModelViewSet): serializer_class = PresetSerializer queryset = Preset.objects.all() # Filtering presets depending on the user # requested it def get_queryset(self): if self.request.user.is_authenticated: return self.queryset.filter(user=self.request.user) return Preset.objects.none()

    Setting up view routes

    And the final touch. To finally see the REST API in action, we need to include the previously created view class, PresetModelView. To do this, add a new router to your application's urls.py file:
    from django.urls import path, include from rest_framework import routers from Backend import views router = routers.DefaultRouter() router.register(r'presets', views.PresetModelView, 'preset') urlpatterns = [ ... path('api/', include(router.urls)), ... ]
    Okay, done. Let's see what we've got. Go to localhost:8000/api/ , you'll see something like this:
    As you can see from the image, we've successfully connected and configured our route. Let's go to any of the provided links, for example, localhost:8000/api/preset/. So, I have two accounts, dima and some, each with its own presets. Let's see how user filtering works:
    User some
    User dima
    As you can see, the first user has only one preset with ID 3. The second has two presets with IDs 1 and 2.

    Working with the API from the client-side

    Working with the API from the client-side is very simple. You just need to make the appropriate AJAX request and process the response. For example, this will get all available records in the Preset model.
    axios.get("/api/preset/", { headers: { "accept": "application/json", "Content-Type": "application/json", }}) .then( resp => { // Your code }) .catch( error => { // Your error code }

    Additional REST Framework Configuration

    You're probably wondering: This all sounds great, but you just want to get the JSON file on the client side and do what you're supposed to. I was also itching for this, and I found a rather elegant solution to this problem.
    Look, in development mode, we'll see previous pages in images, but if we change the mode (i.e., set debug=False in settings.py), we'll get responses like this:
    I have a special extension in Firefox that creates this beautiful thing. It's called JSONView, by the way, and it's also available for Chrome.
    To achieve this, simply add the following lines to the end of your settings.py file:
    if not DEBUG: REST_FRAMEWORK = { # Need to be specified explicitly, otherwise for everyone will be available HTML version of REST framework 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ] }
    We simply change the default renderer and get what we get... a JSON file.

    Conclusion

    So, we've finished setting up our website's API using the Django REST framework. Sure, it might seem a bit confusing and overly complicated at first, but trust me, when your project becomes a little more complex than a single-page landing page, you'll immediately remember the REST framework. It's not so complicated after all ( • • )

    Do not forget to share, like and leave a comment :)

    Comments

    (0)

    captcha
    Send
    LOADING ...
    It's empty now. Be the first (o゚v゚)ノ

    Other

    Similar articles


    How to make django authentication system with forms

    Clock
    16.10.2023
    /
    Clock
    11.03.2026
    An eye
    690
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    Implement a user authentication system. For this purpose, a registration form and login form are created on the website timthewebmaster.com.

    React and Django REST API. How to integrate one into another and how to use

    Clock
    24.07.2024
    /
    Clock
    11.03.2026
    An eye
    614
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    In this article, I will describe a process of integrating the React framework with the Django website. We will configure a communication API between both of them. Also, a TailwindCSS …

    How to integrate React with a Django project, p. 1

    Clock
    03.08.2024
    /
    Clock
    11.03.2026
    An eye
    735
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    In this article, you will know the way to integrate the React framework into a Django project. As a result, you will get a full-stack app/website. Also in the article, …

    How to add translations(localisation) for your telegram bot in aiogram/python + i18n

    Clock
    14.01.2025
    /
    Clock
    11.03.2026
    An eye
    3751
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    In this article, I will show you how to make translations(localisation) for telegram bots made in aiogram/python. And I will do it using the Babel (+ i18n) package. You will …

    How to implement More button (loading more posts for pagination). Using Django, REST API, HTMx

    Clock
    01.04.2025
    /
    Clock
    24.03.2026
    An eye
    624
    Hearts
    0
    Connected dots
    0
    Connected dots
    0
    Connected dots
    0
    In this article I will describe a way how you can implement asynchronous loading of content (articles) using the "More" button, which is made using Django, REST API, HTMx and …

    Used termins


    Related questions