“Creating Your First REST API with Django: A Beginner’s Guide”

Pavan Sai Bolliboina
5 min readJun 14, 2024

--

Welcome Back! Creating a Sample REST API with Django and Django REST Framework

Hello everyone, and welcome to my second post on creating REST APIs with Django. In this post, I will guide you through the process of building a small sample REST API. If you are new here and need to set up the environment, please check out my previous post here

What is a REST API?

A REST API (Representational State Transfer Application Programming Interface) is a way for two computer systems to communicate over HTTP in a manner similar to web browsers and servers. REST APIs are designed to take advantage of existing protocols and can be used to perform CRUD (Create, Read, Update, Delete) operations on data. So this the basic api concept and right now lets Dive in to creating one.

API Creation:

Following the previous setup, we now have Project 0 and app1 ready. Let's dive into creating a sample API using Django and Django REST Framework.

Step 1: Define Your Models

First, we need to define our data models. Open the models.py file in your Django app and define the necessary models. Below is a sample code snippet where I have created a PersonalInfo model with fields such as name, email, phone, about, linkedin, and github.

#Project0>app1>models.py # this is my directory structure

from django.db import models


# Create your models here.
class PersonalInfo(models.Model):
name = models.CharField(max_length=20)
email = models.EmailField()
phone = models.CharField(max_length=20)
about = models.TextField()
linkedin = models.URLField()
github = models.URLField()

If you’re curious about the specific fields like CharField, EmailField, TextField, and URLField, don’t worry. I’ll cover those in a separate post where I’ll explain what each of these fields is and why we use them. This post focuses on creating a sample API to help you understand the flow and execution process.

Step 2: Define Your Serializers

Now that we have defined our models, we need to serialize the data we get from these models. Not ringing any bells? Don’t worry. Serialization is the process of converting complex data types, such as querysets and model instances, into JSON data types that can be easily rendered into a format suitable for client-side consumption.

Serialization is essential because it allows us to transform the data stored in our database into a structured format (JSON) that can be easily used in web applications. This process is crucial for developing APIs, as it enables seamless communication between the server and client.

So, now we will create serializers for our models, which will handle this conversion process. By doing this, we’ll ensure that our API can effectively send and receive JSON data.

To create serializers lets make a new file in our app1 called serializers.py

Before creating serializers we must import serializers from rest_framework and our models from our models.py file below is a sample code snippet Where i have created my serializers.

from rest_framework import serializers
from .models import PersonalInfo

class PersonalInfoSerilaizer(serializers.ModelSerializer):

class Meta:
model = PersonalInfo
fields ='__all__'

again don’t worry about those fields and models i will cover each and every topic in depth in my dedicated posts on views, models, serializers and url’s just understand the flow that after creating models we need to serialize them.

Step 3: Define Your Views

Now that we have serialized our data we need to view our data. So in order to do that we need to create viewsets. Before that we need to import our models from models.py and serializers from our serializers.py files. lets do that in our views.py file. Below is the snippet code where i have created my viewsets.

from rest_framework import viewsets
from .models import PersonalInfo
from .serializers import PersonalInfoSerilaizer

class PersonalInfoViewSet(viewsets.ModelViewSet):
queryset = PersonalInfo.objects.all()
serializer_class = PersonalInfoSerilaizer

Viewsets in Django REST Framework provide CRUD (Create, Retrieve, Update, Delete) operations by default, making it easier to interact with our API endpoints.

Step 3: Define Your Url’s

With our views defined, the next logical step is to set up the URLs in our urls.py file. This involves importing the required viewsets from views.py and certain pertinent classes from rest_framework.routers. Below is the code snippet where i have defined my url’s.

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import PersonalInfoViewSet

router = DefaultRouter()
router.register(r'personalinfo', PersonalInfoViewSet)


urlpatterns = [
path('', include(router.urls)),
]

These API URLs are based on the registered viewsets, which help in streamlining the API endpoint configuration process.

Step 4: Define Your app url’s in Project urls

Now that we have defined our URLs in our app1/urls.py file, it’s essential to include these URLs in our project’s main urls.py file (project0/urls.py). This ensures that when a user accesses our project’s URL, the application knows where to route the request by searching through our project’s main URL configuration.

This practice helps in organizing and centralizing the URL configuration for our entire Django project. So lets open up our project0/urls.py file. Below is my code snipped to define our app1 urls.py file to project0/urls.py file

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('app1.urls')),
]

here you can observe that we just included our app1.urls file with include function which we have imported from django.urls.

Hurray…..! We have created a simple API for PersonalInfo using Django and Django REST Framework, including model definition, serialization, views and URL configuration.

Step 3: Test Your API

Lets test our API by running python manage.py runserver command in terminal. By clicking on the ip address generated in terminal along with our path /api we will get the response as shown below.

This is the root view of our API. Since we are using a DefaultRouter, clicking on http://127.0.0.1:8000/api/personalinfo takes you to our main API endpoint, which is used for performing CRUD operations. This is our output

Here you can see the details of the name and other fields which are returned when I entered them in the fields below. After clicking the POST button, the details are displayed as shown in the picture above. You can also see another example in the picture below.

Yip yip hurray! We have successfully created a REST API! 🎉

Thanks for being here if you love my work please do follow me on

Medium: https://pavansaibolliboina.medium.com/

LinkedIn: www.linkedin.com/in/bolliboinapavansai

Support me on : Buy me a coffee here

--

--