understanding rest apis in django€¦ · django rest framework it has a web browsable api built in...

25
Understanding REST APIs in Django Abhijit Bonik Indian Institute of Technology Bombay May 21, 2019

Upload: others

Post on 15-Aug-2020

33 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Understanding REST APIsin Django

Abhijit Bonik

Indian Institute of Technology Bombay

May 21, 2019

Page 2: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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.

Page 3: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Guiding Principles of REST

Client–Server

Stateless

Layered system

Uniform interface

Cacheable

Code on demand (optional)

Page 4: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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

Page 5: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Django

Page 6: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Features in Django

An Admin interface

Session, User management, role-based permissions

Template engine

Form handling

Object-relational mapping (ORM)

Testing Framework

Internationalization

Page 7: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

MVT Framework

Model (ORM, Database)

View (functions, classes)

Template (HTML)

Page 8: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

The request-response lifecycle of a Django

Figure: Execution Flow

https:

//cloudera.github.io/hue/docs-2.0.1/sdk/django_request.png

Page 9: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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.

Page 10: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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.

Page 11: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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.

Page 12: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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 %}

Page 13: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Advance Concepts

Page 14: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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)

Page 15: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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

Page 16: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Generic Class based Views (GCBV)

They can speed up development. Following are some mostly used GCBV

CreateView,

DetailView

DeleteView

FormView

UpdateView

ListView.

Page 17: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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’

Page 18: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Django Rest API

Page 19: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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.

Page 20: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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’)

Page 21: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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’),

]

Page 22: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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)

Page 23: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

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

Page 24: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Dive into Code

https://github.com/abhisgithub/SummerProjectBlog

Page 25: Understanding REST APIs in Django€¦ · Django Rest Framework It has a Web browsable API Built in authentication scheme such as TokenAuthentication, BasicAuthentication, Sessionbased

Let’s Code