Django Rest Framework — Creating a Simple API in 15mins With DRF
What is the REST API?
To know what is REST API, let’s first understand what is an API. An API is a set of code that allows much software to communicate with each other. It is abbreviated as Application Program Interface. Then what is REST API? REST API is an architectural style that defines a set of rules to be used while creating web services. If an API follows these rules, then the API is a REST API. REST API is abbreviated as REpresentational State Transfer.
The four main API requests are GET, POST, PUT, DELETE.
GET —This request is made when we wanna request some data from the server. Eg: Fetching weather forecast from the weather API.
POST — This request is made when we wanna add data to the server. Eg: User Registration and Login.
PUT — This request is for changing any Existing information in the server. Eg: Updating User Profile.
DELETE — As the name indicates, this request is made where we wanna delete any existing information.
In this blog, I just explaining how to create a simple REST API with Django’s Django Rest Framework.
- Create a Django Project
So now let’s start creating our Django project. I am creating a Django project named drf
. After creating, just migrate the project.
$ django-admin startproject drf
$ cd drf
$ python3 manage.py migrate
$ python3 manage.py runserver
2. Install Django Rest Framework
Django Rest Framework is one of the toolkits built for developing web APIs.
So now let’s install Django Rest Framework.
$ pip3 install djangorestframework markdown django-filter
This command will install the Django rest framework into our project.
Now add our restframework
to the installed apps.
drf/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # make Sure to add this line
]
3. Creating a Model
Create a new App student
in the drf
project where we’ll be creating our model.
$ python3 manage.py startapp student
This command will create a new app named student
. Now let’s start creating our model. Don't forget to add the app to our installed apps.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'student', # make Sure to add this line
]
Now I am just including my new App’s urls.py
in the project level urls.py
file.
drf/urls.py
from django.conf.urls import url
from django.urls import path, include
from django.contrib import adminurlpatterns = [
url(r'^admin/', admin.site.urls),
path('student/', include('student.urls'))
]
Now let’s start creating our model.
student/models.py
from django.db import models# Create your models here.
class Student(models.Model):
student_reg_number = models.TextField(unique=True)
student_name = models.TextField()
student_email = models.TextField()
student_mobile = models.TextField(null=True)
created_at = models.DateTimeField(auto_now=True)
After creating the model file just migrate.
$ python3 manage.py makemigrations
$ python3 manage.py migrate
The command will initially create a new migration file and then migrate our changes to the database.
4. Creating API and Serializer Class:
Now everything is good. We have created our model successfully. Now let’s get into the API section.
To create an API we need two files, serializer
file, and theapi or view
file. Basically, the serializer
is something that converts the instance given to the API into python or the native language’s datatype that can be converted into json
or xml
format. A api
is the initial point of contact from the URL. We can also use the default view.py
file. But I am not using it to create API. Each and every programmer have their own way of coding. I prefer to keep api
as a separate file.
So now let’s create api.py
and serializer.py
files in the student
app. So the app structure must be student/api.py
and student/serializer.py
.
student/serializer.py
from rest_framework import serializers
from .models import Studentclass StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
student/api.py
from rest_framework import generics
from rest_framework.response import Response
from .serializer import StudentSerializer
from .models import Studentclass StudentApi(generics.ListCreateAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
Here the ListCreateAPIView
is the class that helps us to create both POST and GET requests.
Now map our StudentApi
with a URL as shown.
student/urls.py
from django.urls import path
from .api import StudentApiurlpatterns = [
path('api',StudentApi.as_view()),
]
Now your code is ready. Just run your server. Navigate to the browser and open http://localhost:8000/student/api. You should see a screen as shown. If you have used node before, you would have used something called Swagger
. It is an online UI client to make Http requests. Similarly, DRF provides the same, as an inbuilt functionality where you can make all the PUT, GET, POST, and DELETE requests.
Also, you can check if it works with Postman. The below image is a demonstration for the POST request.
This image is a demonstration for GET request.
Another cool feature I personally like in DRF is that it handles errors. In my model, I have created student_reg_number
to be unique and required. So if the request from the client didn’t send the required field, it sends error response. Cool right. I found it difficult with node js. But now the node has some packages to handle it.
In my next blog, I will be performing CRUD functionality with Django Rest Framework. Stay Connected.
Feel free to contact me for any queries.
Email: sjlouji10@gmail.com
Linkedin: https://www.linkedin.com/in/sjlouji/
Complete Code can be found on my Github: https://github.com/sjlouji/Django---DRF-basic-Rest-API-.git
Happy coding…