How to Build a RESTAPI with Django

Written by asijapratik | Published 2023/01/30
Tech Story Tags: django | rest-api | python | python-programming | python3 | python-framework | python-tutorials

TLDRIn this article, we will go through the process of building a RESTful API using Django, one of the most popular web frameworks for Python. The first step in building a Django-based REST API is to create a new Django project. We will use the Django REST framework to create our serializers and views for our API.via the TL;DR App

RESTful APIs have become an essential part of modern web development. They allow for easy communication between different systems and platforms, and are a great way to provide access to your data and functionality to third-party developers.

In this article, we will go through the process of building a RESTful API using Django, one of the most popular web frameworks for Python.

Step 1: Setting up a Django Project

The first step in building a Django-based REST API is to create a new Django project. To do this, you will need to have Django installed on your system.

You can install it using pip by running the following command:

pip install django

Once you have Django installed, you can create a new project by running the following command:

django-admin startproject myproject

This will create a new directory called myproject, which will contain the basic structure of a Django project.

Step 2: Creating a Django App

The next step is to create a new app within our project. An app is a self-contained module within a Django project that can contain models, views, and templates.

To create a new app, navigate to the root of your project directory and run the following command:

python manage.py startapp myapp

This will create a new directory called myapp, which will contain the basic structure of a Django app.

Step 3: Defining Models

In this step, we will define the models for our API. Models are Python classes that define the structure of the data that our API will work with. In this example, we will create a simple model called “Task” that has a title and a description.

To define the Task model, open the myapp/models.py file and add the following code:

from django.db import models

class Task(models.Model):title = models.CharField(max_length=255)description = models.TextField()

This defines a new model called Task that has two fields, title, and description. The CharField is used for short strings, and the TextField is used for longer strings.

Step 4: Creating Serializers

In this step, we will create serializers for our models. Serializers are used to convert the data from our models into a format that can be easily rendered into JSON or XML.

We will use the Django REST framework to create our serializers.

To install the Django REST framework, run the following command:

pip install djangorestframework

Once the framework is installed, create a new file called serializers.py in the myapp directory, and add the following code:

from rest_framework import serializersfrom .models import Task

class TaskSerializer(serializers.ModelSerializer):class Meta:model = Taskfields = ('id', 'title', 'description')

This creates a new serializer class called TaskSerializer that is based on the Task model we defined earlier. The fields attribute is used to specify which fields from the model should be included in the serialized data.

Step 5: Creating Views

In this step, we will create views for our API. Views handle the logic for handling incoming requests and returning responses. We will use the generic views provided by the Django REST framework to handle the common CRUD (Create, Retrieve, Update, Delete) operations.

from rest_framework import genericsfrom .models import Taskfrom .serializers import TaskSerializer

class TaskList(generics.ListCreateAPIView):queryset = Task.objects.all()serializer_class = TaskSerializerclass TaskDetail(generics.RetrieveUpdateDestroyAPIView):queryset = Task.objects.all()serializer_class = TaskSerializer

This code defines two views, TaskList and TaskDetail, that handle the List and Retrieve, Update and Delete operations respectively. The views inherit from the generic views provided by the Django REST framework and use the TaskSerializer and the Task model to handle the data.

Step 6: Setting up URL routing

In this step, we will set up URL routing for our API. URL routing maps URLs to views so that when a user visits a certain URL, the corresponding view is called.

Open the myproject/urls.py file and add the following code:

from django.urls import path,

includefrom rest_framework.routers

import DefaultRouterfrom myapp.views import TaskList, TaskDetail

router = DefaultRouter()router.register(r'tasks', TaskList, basename='task')urlpatterns = [path('', include(router.urls)),]

This code creates a new router object and register the TaskList view to handle the tasks URL. The include function is used to include the URLs from the router in the main URL patterns.

Step 7: Testing the API

Now that we have set up our API, we can test it by starting the development server:

python manage.py runserver.

And then visiting http://localhost:8000/tasks/ in the browser. You should see a JSON response of all the tasks, and you can also test other CRUD operations by visiting the appropriate URL.

That concludes the process of building a basic REST API using Django.

This example demonstrates the basic structure of a Django-based REST API, but it can be easily expanded to include more models, views, and functionality. Some next steps would be to add authentication and permissions to the API to handle different types of requests and responses and to create a more complex data model. Django REST framework also provides a lot of other features such as pagination, filtering, and throttling that can be used to improve the functionality of your API.

It’s important to note that building a REST API is just one of the many things that you can do with Django. Django is a powerful web framework that can be used for a wide variety of web development tasks such as building web applications, e-commerce sites, and content management systems. By understanding the basics of building a REST API with Django, you will be well on your way to becoming a proficient Django developer.


Also published here.


Written by asijapratik | I am a software engineer. I work as a freelance writer too and love to write technical blogs and articles.
Published by HackerNoon on 2023/01/30