The Python web framework Django is extensively used nowadays. Working with various APIs in the system, Django provides a Rest API framework that makes it easier for a developer to perform different operations. Django REST Framework is an easy, flexible, and powerful toolkit for building Web APIs. By using DRF, we can convert the entire non-RESTful application into a RESTful one.
If you don't know anything then don't worry about it. I'll help you to cover all topics and make you knowledgeable with Rest Framework at the end of this article.
In this article, we'll cover the following topics:
- What is API?
- What is REST Framework?
- What is the REST API?
- Installation of Rest Framework
- Django rest framework application
What is API?
API refers to Application Programming Interface. Let's break this into parts-
Application: If you using the smartphones then you must aware of applications like, Social apps, Games, or any other software that you use in your day-to-day life.
Programming: It is basically a set of instructions that we tell to computers to perform some specific tasks.
Interface: It is the point where two or more applications or programs interact with each other.
According to Google, API is a set of subroutine definitions, protocols, and tools for building application software. An API makes it easier for developers to use certain technologies in building applications by using certain predefined operations.
What is REST Framework?
It describes an architecture which stands for REpresentational State Transfer. It is used for web-based architecture for data communication and uses HTTP to make calls between machines.
HTTP has several request methods for a REST architecture.
- GET - By default
- POST
- PUT
- DELETE
- CONNECT
- HEAD
- OPTION
- TRACE
- PATCH
The most commonly used HTTP methods in a REST-based architecture –
GET: It only fetches the data from server to client machine.
POST: It provides data from the server and can add new data to the server.
PUT: It used to update the data to the server.
DELETE: To delete the data from the server.
Advantages of using REST Framework
- Gives scalability to your application
- Authentication policies of Rest framework include OAuth1a
and OAuth2 packages.
- Both ORM and Non-ORM data sources supported by
serialization.
- Huge community support and great documentation.
- Used and trusted by the top international level companies like Mozilla, Red Hat, Heroku, and Eventbrite.
What is the REST API?
When web services used REST architecture, they are called RESTful APIs or REST APIs.
A REST API is a set of web addresses that respond with pure information, not formatted web pages. An API returns a JSON, which is common format. You'll see all of the information surrounded by quotation, {}, [], and descriptive titles for each bit of information.
This is how API returns JSON data:
[ { "id": 2, "std_id": 1, "firstname": "Bharat", "lastname": "Vora", "email": "bharatvora814@gmail.com" } ]
Let's Code
Make sure your system has the following packages:
- Python 3.8.1
- pipenv
- django 3.0.8
Let’s start over by creating your awesome Python application. First, spawn a shell in a virtual environment to isolate the development of this app:
$ pipenv shell
Install Django-rest-framework -
$ pip install djangorestframework
Create a new Django project -
$ django-admin startproject restframework
also, create a new application in this -
$ python manage.py startapp webapp
Now, if you run the server, you'll see the default django homepage.
$ python manage.py runserver
Now, update app's setting.py file -
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'webapp',
]
Add below code to webapp/model.py -
from django.db import models
# Create your models here.
class students(models.Model):
std_id = models.IntegerField()
firstname = models.CharField(max_length=10)
lastname = models.CharField(max_length=10)
email = models.EmailField(max_length=30)
def __str__(self):
return self.firstname
update webapp/admin.py -
from django.contrib import admin
from .models import students
# Register your models here.
admin.site.register(students)
We have done with our model and now we have to make migration so that it will create a table structure according to what we define in models.py
$ python manage.py makemigration
$python manage.py migrate
Django provides pretty good admin panel where an admin can Add, Delete, Update users, and groups. For this, let's create superuser -
$ python manage.py createsuperuser
*It will ask for some details like username, email, and password.
Again, start the server and go to http://localhost:8000/admin. Login with your credential and add some student’s details.
Create a new file at webapp/serializers.py -
from rest_framework import serializers
from . models import students
class studentsSerializer(serializers.ModelSerializer):
class Meta:
model = students
#fields = ('firstname','lastname')
fields = '__all__'
Add the code in webapp/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import students
from .serializers import studentsSerializer
# Create your views here.
class studentList(APIView):
def get(self,request):
student1 = students.objects.all()
serializer = studentsSerializer(student1, many=True)
return Response(serializer.data)
def post(self):
pass
add a route to your project's urls.py -
from django.contrib import admin
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from webapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('student/', views.studentList.as_view()),
]
Boooom !!
You created the Django application with DRF. Go to the browser and check if you have access to data!
You'll see something like this -
Thank you 😍💙