Understanding REST APIsin Django
Abhijit Bonik
Indian Institute of Technology Bombay
May 21, 2019
REST API
It is an architecture style for designing loosely coupled applicationsover HTTP
Any application that can understand internet’s Hypertext TransferProtocol (HTTP) can communicate with each other.
REST is often used in the development of web services.
REST is also a language-independent architectural style. so anylanguage - Python, Java, .NET, etc. can be used.
Guiding Principles of REST
Client–Server
Stateless
Layered system
Uniform interface
Cacheable
Code on demand (optional)
HTTP Status Codes
HTTP response status codes indicate whether a specific HTTP requesthas been successfully completed. Responses are grouped in five classes:
1xx: Informational responses
2xx: Successful responses
3xx: Redirects
4xx: Client errors
5xx: Servers errors
Django
Features in Django
An Admin interface
Session, User management, role-based permissions
Template engine
Form handling
Object-relational mapping (ORM)
Testing Framework
Internationalization
MVT Framework
Model (ORM, Database)
View (functions, classes)
Template (HTML)
The request-response lifecycle of a Django
Figure: Execution Flow
https:
//cloudera.github.io/hue/docs-2.0.1/sdk/django_request.png
Models
You will define all your models in models.py file for the respective module.
from django.db import models
from django.contrib.auth.models import User
class Blog(models.Model):
title = models.CharField(max_length=100)
body = models.TextField(null=True)
image = models.ImageField(null=True,upload_to=’blog’)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(User)
Note: Every class you define in models.py file will create a table in thedatabase.
Views
Views are nothing but functions defined in view.py file of your module.
from .models import Blog
def get_all_blogs(request):
blogs=Blog.objects.all()
return render(request,’blogs.html’,{’blogs’:blogs})
Note: Each view function accepts an http request , does all processing,make a call to the database(models) if needed and gives a http response.
URLs
The urls are defined in the variable ’urlpatterns’
from blogs import views
urlpatterns = [
url(r’^blogs/$’, views.get_all_blogs,
name = ’blogs’),
]
Django search for all urls requested in this variable.
Template
The template file will display the value of variables or data it has receivedfrom the view function. Following is a interns.html file -
{% extends ’base.html’ %}
{% for blog in blogs %}
{{ blog.title }}
{{ blog.body }}
{% endfor %}
Advance Concepts
Class based views
It extends the View class.
The requests are handled inside class methods named after the HTTPmethods- get, post, put, head, etc
So no conditional check is required
Two types -
1 Class-Based Views (CBV)2 Generic Class-Based Views (GCBV)
Create interns using- Class based views
from django.views.generic import View
from .forms import NewBlogForm
class CreateBlogView(View):
def post(self, request):
#write your post logic here
def get(self, request):
#write you get logic
Generic Class based Views (GCBV)
They can speed up development. Following are some mostly used GCBV
CreateView,
DetailView
DeleteView
FormView
UpdateView
ListView.
Generic Class based views - List View
from django.views.generic import ListView
from .models import Blogs
class BologListView(ListView):
model = Blogs
context_object_name = blogs
template_name = blogs.html’
Django Rest API
Django Rest Framework
It has a Web browsable API
Built in authentication scheme such as TokenAuthentication,BasicAuthentication, Sessionbased
Serialization that supports both ORM and non-ORM data sources.
Serializers
Serializers allow complex data such as querysets and model instances to beconverted to native Python data types that can then be easily renderedinto JSON, XML or other content types.
from rest_framework import serializers
from .models import Blog
class BlogSerializer(serializers.ModelSerializer):
class Meta:
model = Articles
fields = (’pk’,’title’, ’body’, ’image’,’created_by’)
Class based Viewsets
from rest_framework import viewsets
from .serializers import BlogSerializer
from .models import Blog
class BlogListApiView(generics.ListAPIView):
queryset = Blog.objects.all()
serializer_class = BlogSerializer
permission_classes = (IsAuthenticated,)
Urls – Link your api view to url
urlpatterns = [
url(r’^api/blogs/$’, views.BlogListApiView.as_view(), name=’blogs_api’),
]
Using function base view
@api_view([’GET’, ’POST’])
def blog_api(request):
if request.method == ’GET’:
blogs = Blogs.objects.all()
serializer = BlogSerializer(interns, many=True)
return Response(serializer.data)
elif request.method == ’POST’:
serializer = BlogSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,
status=status.HTTP_201_CREATED)
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
Where we are now
What are models, views, templates, urls.
What is Class Based and Generic Class Based Views
What is Rest APIs
How to create a Rest API Using DRF
What are Serializers and Generic API View
Dive into Code
https://github.com/abhisgithub/SummerProjectBlog
Let’s Code