Download as pdf or txt
Download as pdf or txt
You are on page 1of 122

MOHAN S.

REDDY

REST API (Django Rest Framework-DRF)


Introduction:

 API stands for Application Programming Interface.


 It is software that enables communication between the two or more
applications.
 When you use an application on your mobile phone, the application connects
to the Internet and sends data to a server.
 The server then retrieves that data, interprets it, performs the necessary
actions and sends it back to your phone.
 The application then interprets that data and presents you with the
information you wanted in a readable way.
 This is what an API is - all of this happens via API
 Django REST is a powerful Django-based framework that the developer
uses to create the APIs.
 Django Rest Framework lets you create RESTful APIs: A way to transfer
information between an interface and a database in a simple way.
 In Django REST, REST stands for Representational State Transfer. It is
used for web-based architecture for data communication.
 REST is an architectural style, not a protocol.
 Django REST framework(DRF) is an open source, flexible and fully-
featured library with modular and customizable architecture that aims at
building web APIs and uses Python and Django.

Advantages of DRF:

 DRF allows the flexibility to extend and customize the framework’s tools
according to programmer’s demands that greatly reduces development time.
 It also provides the support of testing, debugging and caching.
 Simplicity, flexibility, quality, and test coverage of source code.
 Powerful serialization engine compatible with both ORM and non-ORM
data sources.
 Pluggable and easy to customize validators and authenticators.
 Generic classes for CRUD operations.
 Clean, simple, views for Resources, using Django's new class based views.
MOHAN S.REDDY

API types:

1. Private :It can be used within the organization


2. Partner: It can be used within business partners
3. Public: It can be used any third party developers

How API works:

 Client sends HTTP request to API.


 API will interact with web application
 Web application will interact with database if it is required.
 Web application provides required data to API.
 API returns data to client.

REST API:
 REST API is an architectural style for an application programming interface
(API) that uses HTTP request to access and use data.

 When web services use REST architecture, they are called Restful APIs or
REST APIs.
 A REST API is a set of web addresses that respond with pure information.
 API returns JSON or XML, which is common format.
MOHAN S.REDDY

 We can see all the information enclosed within {},[ ].

JSON:

 JSON is an open standard file format and data interchange format that uses
human-readable text to store and transmit data objects consisting of attribute
value pairs.
 JavaScript Object Notation (JSON) is a standard text-based format for
representing structured data based on JavaScript object syntax. It is
commonly used for transmitting data in web applications (e.g., sending some
data from the server to the client, so it can be displayed on a web page.

XML:

 XML (Extensible Markup Language) is used to describe data. The XML


standard is a flexible way to create information formats and electronically
share structured data via the public internet, as well as via corporate
networks.

HTTP Methods :( GET, POST, PUT, PATCH, DELETE)

API Resource:
MOHAN S.REDDY

Note: Here api is not compulsory, but endpoint or resource is must.

Installing DRF:

 To install DRF first we have to install python and django framework.


 Install DRF using pip:
pip install djangorestframework

Include DRF in django project:

 INSTALLED_APPS=[
‘rest_framework’
]

Creating API:

 Go to command prompt and create a django project


Ex: django-admin startproject Restproject
 Create application under Restproject
Ex: cd Restproject
Ex: python manage.py startapp Restapp
 Open Restproject in pycharm editor
 Install Restapp under settings.py

Settings.py:
MOHAN S.REDDY

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Restapp',
'rest_framework',
]

models.py:

from django.db import models

# Create your models here.


class Employees(models.Model):
empid=models.IntegerField()
ename=models.CharField(max_length=20)
eaddress=models.CharField(max_length=20)
email=models.EmailField(max_length=30)

def __str__(self):
return self.ename

admin.py :

from django.contrib import admin


from Restapp.models import Employees

# Register your models here.


admin.site.register(Employees)

Now go to terminal and then type the following commands

 Python manage.py makemigrations


MOHAN S.REDDY

 Python manage.py migrate


 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Now go to admin panel by login with super user login id and password
and insert few records.

Note: to convert model data into JSON format then we use serializers.

 Add a new python file under the app with the name serializers.py

serializers.py:

from rest_framework import serializers


from Restapp.models import Employees

class empSerializer(serializers.ModelSerializer):

class Meta:
model=Employees
fields='__all__'

views.py:

from rest_framework.views import APIView


from rest_framework.response import Response
from Restapp.models import Employees
from Restapp.serializers import empSerializer

# Create your views here.


class empDetails(APIView):

def get(self,request):
emp=Employees.objects.all()
serializer=empSerializer(emp,many=True)
MOHAN S.REDDY

return Response(serializer.data)

def post(self):
pass

urls.py:

from django.contrib import admin


from django.urls import path
from Restapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('emp/',views.empDetails.as_view()),
]

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/emp

Serializers:

 Serializers allow complex data such as query sets and model instances to be
converted to native python data types that can then be easily rendered into
JSON, XML or other content types.
 Serializers also provide deserialization, allowing parsed data to be converted
back into complex types.
 The process of converting complex data like query sets and model instances
to python data types is called serialization.

JsonRenderer:

 It is used to render serialized data into JSON.

Creating API with function based views:

 Create a new django project and application.


MOHAN S.REDDY

 Go to settings.py

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]

models.py:
from django.db import models

# Create your models here.


class Employee(models.Model):
ename=models.CharField(max_length=20)
eaddress=models.CharField(max_length=20)
email=models.CharField(max_length=20)

admin.py:
from django.contrib import admin
from myapp.models import Employee

# Register your models here.


@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
list_display =['id','ename','eaddress','email']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


MOHAN S.REDDY

 Python manage.py migrate


 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Now go to admin panel by login with super user login id and password
and insert few records.

serializers.py:

from rest_framework import serializers

class EmpSerializer(serializers.Serializer):
id=serializers.CharField(max_length=20)
ename=serializers.CharField(max_length=20)
eaddress=serializers.CharField(max_length=20)
email=serializers.CharField(max_length=20)

views.py:
from myapp.models import Employee
from myapp.serializers import EmpSerializer
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse

# Create your views here.

def emp_details(request,pk):
emp=Employee.objects.get(id=pk)
#print(emp)
serializer=EmpSerializer(emp)
#print(serializer)

json_data=JSONRenderer().render(serializer.data)
#print(json_data)
return
HttpResponse(json_data,content_type='application/js
MOHAN S.REDDY

on')

def emp_all_details(request):
emp=Employee.objects.all()
serializer=EmpSerializer(emp,many=True)

json_data=JSONRenderer().render(serializer.data)
return
HttpResponse(json_data,content_type='application/js
on')

urls.py :

from django.contrib import admin


from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('emp/<int:pk>',views.emp_details),
path('empall/',views.emp_all_details),
]

Note: create a new python file with the name test.py

test.py :

import requests

URL="http://127.0.0.1:8000/emp/1"
r=requests.get(url=URL)
emp_data=r.json()
print(emp_data)

 Go to terminal and run test.py


 python test.py
MOHAN S.REDDY

Note: from test.py file we are requesting to api to get employee data and api will
send request to django application.

De serialization:

 Serializers in Django REST Framework are responsible for converting


objects into data types understandable by front-end frameworks.
 Serializers also provide deserialization, allowing parsed data to be converted
back into complex types, after first validating the incoming data.

 The io module provides Python's main facilities for dealing with various
types of I/O.
 Python IO module allows us to manage the file-related input and output
operations.
 A stream is basically a sequence of data. Whatever data we use in our
programming it flows through a stream.
MOHAN S.REDDY

 A stream can be thought of as a channel connecting a processor or logic unit


(where data is processed according to the instructions) and input and output
devices.
 BytesIO is used for binary data.
 BytesIO can be used in place of a file object. So you have a function that
expects a file object to write to. Then you can give it that in-memory buffer
instead of a file.
 BytesIO can be useful when you need to pass data to or from an API that
expect to be given a file object.
 BytesIO implements read and write bytes data in memory.
 We create a BytesIO object and then write some bytes data into it.
 Please note that instead of writing a string, you write utf-8 encoded bytes
with the BytesIO object.

JSON Parser ():

 It parses the incoming request JSON content into python content type dict.
 JSONParser. Parses JSON request content. Request.data will be
populated with a dictionary of data.
 Data parsing is the process of taking data in one format and
transforming it to another format.

Ex: Creating or Inserting Data.

 Create a new project and application.

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
MOHAN S.REDDY

'myapp.apps.MyappConfig',
]

models.py:

from django.db import models

# Create your models here.


class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail=models.CharField(max_length=20)
age=models.IntegerField()

admin.py:

from django.contrib import admin


from myapp.models import Manager
# Register your models here.

@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display = ['name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
MOHAN S.REDDY

Create a new python file with the name serializers.py.

serializers.py:

from rest_framework import serializers


from myapp.models import Manager

class ManagerSerialzer(serializers.Serializer):
name=serializers.CharField(max_length=20)
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()

def create(self, validated_data):


return
Manager.objects.create(**validated_data)

views.py:

from django.shortcuts import render


import io
from rest_framework.parsers import JSONParser
from myapp.serializers import ManagerSerialzer
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse
from django.views.decorators.csrf import
csrf_exempt

# Create your views here.


@csrf_exempt
def create_Manager(request):
if request.method=='POST':
jsondata=request.body
MOHAN S.REDDY

stream=io.BytesIO(jsondata)
py_data=JSONParser().parse(stream)
serializer=ManagerSerialzer(data=py_data)
if serializer.is_valid():
serializer.save()
result={'message':'Data inserted into
database'}
jsondata=JSONRenderer().render(result)
return
HttpResponse(jsondata,content_type='application/jso
n')

jsondata=JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')

urls.py:

from django.contrib import admin


from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('createmanager/',views.create_Manager),
]

Create a new python file with the name test.py inside the application.

test.py:

import requests
import json

URL="http://127.0.0.1:8000/createmanager/"
MOHAN S.REDDY

data={
'name':'mohan',
'address':'hyderabad',
'mail':'mohan@gmail.com',
'age':37
}

jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)

 Now start server : python manage.py runserver


 Python test.py( in new terminal window)

CRUD API using Function Based View:

 dumps ( ): It is used to convert python object JSON string.


 loads ( ): It is used to pars JSON string.

Create a new project and application

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]

models.py :
MOHAN S.REDDY

from django.db import models

# Create your models here.


class Employee(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail=models.CharField(max_length=20)
age=models.IntegerField()

admin.py:

from django.contrib import admin


from myapp.models import Employee
# Register your models here.

@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin

Create a new python file with the name serializers.py.

serializers.py:
from rest_framework import serializers
from myapp.models import Employee
MOHAN S.REDDY

class EmployeeSerialzer(serializers.Serializer):
name=serializers.CharField(max_length=20)
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()

def create(self, validated_data):


return
Employee.objects.create(**validated_data)

def update(self, instance, validated_data):

instance.name=validated_data.get('name',instance.na
me)
instance.address =
validated_data.get('address', instance.address)
instance.mail = validated_data.get('mail',
instance.mail)
instance.age = validated_data.get('age',
instance.age)
instance.save()
return instance

views.py:

from django.shortcuts import render


import io
from rest_framework.parsers import JSONParser
from myapp.serializers import EmployeeSerialzer
from myapp.models import Employee
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse
from django.views.decorators.csrf import
csrf_exempt
MOHAN S.REDDY

# Create your views here.


@csrf_exempt
def emp_data(request):
if request.method=='GET':
jsondata=request.body
stream=io.BytesIO(jsondata)
py_data=JSONParser().parse(stream)
id=py_data.get('id',None)
if id is not None:
emp=Employee.objects.get(id=id)
serializer=EmployeeSerialzer(emp)

jsondata=JSONRenderer().render(serializer.data)
return
HttpResponse(jsondata,content_type='application/jso
n')

emp=Employee.objects.all()
serializer =
EmployeeSerialzer(emp,many=True)
jsondata =
JSONRenderer().render(serializer.data)
return HttpResponse(jsondata,
content_type='application/json')

if request.method == 'POST':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
serializer =
EmployeeSerialzer(data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data inserted
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
MOHAN S.REDDY

content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')

if request.method=='PUT':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id=py_data.get('id')
emp=Employee.objects.get(id=id)

#serializer=EmployeeSerialzer(emp,data=py_data,part
ial=True)
serializer = EmployeeSerialzer(emp,
data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data updated
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')

if request.method=='DELETE':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = Employee.objects.get(id=id)
emp.delete()
MOHAN S.REDDY

result = {'message': 'Data deleted from


database'}
jsondata = JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')

urls.py:

from django.contrib import admin


from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('emp/',views.employee_data),
]

Create a new python file with the name test.py inside the application.

test.py:

import requests
import json

URL="http://127.0.0.1:8000/emp/"

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
r=requests.get(url=URL,data=jsondata)
data=r.json()
print(data)

#get_record(1)
#get_record()
MOHAN S.REDDY

def post_record():
data = {
'name': 'kiran',
'address': 'vizag',
'mail': 'kiran@gmail.com',
'age': 28
}
jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)

#post_record()

def update_record():
data = {
'id':1,
'name': 'ramesh',
'address': 'vizag',
'mail':'ramesh@gmail.com',
'age': 45
}
jsondata=json.dumps(data)
r=requests.put(url=URL,data=jsondata)
data=r.json()
print(data)

#update_record()

def delete_data():
data={'id':2}

jsondata=json.dumps(data)
r=requests.delete(url=URL,data=jsondata)
data=r.json()
print(data)
MOHAN S.REDDY

delete_data()

 Now start server : python manage.py runserver


 Python test.py( in new terminal window)

CRUD API using Class Based View:

 dumps ( ): It is used to convert python object JSON string.


 loads ( ): It is used to pars JSON string.

Create a new project and application

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]

models.py :

from django.db import models

# Create your models here.


class Employee(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail=models.CharField(max_length=20)
age=models.IntegerField()
MOHAN S.REDDY

admin.py:

from django.contrib import admin


from myapp.models import Employee
# Register your models here.

@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin

Create a new python file with the name serializers.py.

serializers.py:

from rest_framework import serializers


from myapp.models import Employee

class EmployeeSerialzer(serializers.Serializer):
name=serializers.CharField(max_length=20)
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()

def create(self, validated_data):


return
Employee.objects.create(**validated_data)
MOHAN S.REDDY

def update(self, instance, validated_data):

instance.name=validated_data.get('name',instance.na
me)
instance.address =
validated_data.get('address', instance.address)
instance.mail = validated_data.get('mail',
instance.mail)
instance.age = validated_data.get('age',
instance.age)
instance.save()
return instance

views.py:

from django.shortcuts import render


import io
from rest_framework.parsers import JSONParser
from myapp.serializers import EmployeeSerialzer
from myapp.models import Employee
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse
from django.views.decorators.csrf import
csrf_exempt
from django.utils.decorators import
method_decorator
from django.views import View

# Create your views here.


@method_decorator(csrf_exempt,name='dispatch')
class empdata(View):
def get(self,request,*args,**kwargs):
if request.method == 'GET':
jsondata = request.body
stream = io.BytesIO(jsondata)
MOHAN S.REDDY

py_data = JSONParser().parse(stream)
id = py_data.get('id', None)
if id is not None:
emp = Employee.objects.get(id=id)
serializer = EmployeeSerialzer(emp)
jsondata =
JSONRenderer().render(serializer.data)
return HttpResponse(jsondata,
content_type='application/json')
emp = Employee.objects.all()
serializer = EmployeeSerialzer(emp,
many=True)
jsondata =
JSONRenderer().render(serializer.data)
return HttpResponse(jsondata,
content_type='application/json')

def post(self, request, *args, **kwargs):


if request.method == 'POST':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
serializer =
EmployeeSerialzer(data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data inserted
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')

def put(self, request, *args, **kwargs):


MOHAN S.REDDY

if request.method == 'PUT':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = Employee.objects.get(id=id)
#
serializer=EmployeeSerialzer(emp,data=py_data,parti
al=True)
serializer = EmployeeSerialzer(emp,
data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data updated
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')

def delete(self, request, *args, **kwargs):


if request.method == 'DELETE':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = Employee.objects.get(id=id)
emp.delete()
result = {'message': 'Data deleted
from database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
MOHAN S.REDDY

urls.py:

from django.contrib import admin


from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('emp/',views.empdata.as_view()),

Create a new python file with the name test.py inside the application.

test.py:

import requests
import json

URL="http://127.0.0.1:8000/emp/"

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
r=requests.get(url=URL,data=jsondata)
data=r.json()
print(data)

#get_record(1)
#get_record()

def post_record():
data = {
MOHAN S.REDDY

'name': 'kiran',
'address': 'vizag',
'mail': 'kiran@gmail.com',
'age': 28
}
jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)

#post_record()

def update_record():
data = {
'id':1,
'name': 'ramesh',
'address': 'vizag',
'mail':'ramesh@gmail.com',
'age': 45
}
jsondata=json.dumps(data)
r=requests.put(url=URL,data=jsondata)
data=r.json()
print(data)

#update_record()

def delete_data():
data={'id':2}

jsondata=json.dumps(data)
r=requests.delete(url=URL,data=jsondata)
data=r.json()
print(data)

delete_data()
MOHAN S.REDDY

 Now start server : python manage.py runserver


 Python test.py( in new terminal window)

DRF Validations:

 Validation is the process of checking whether user entered data is correct or


not.
 We can perform validation in 3 different ways
1. Field level validation
2. Object level validation
3. Validators

Field level validation: This can be used to validate specific field

Syntax: def validate_fieldname (self, value):

Here value is the field value which requires the validation.

Object level validation: This can be used to perform validation on all fields or
multiple fields.

Syntax: def validate (self, data):

Here data is python dictionary of field values.

Validators: This can be used to create a validation function with logic that can be
reuse in the application.

Ex:

Note: I recommend executing the above example as it is just by changing

the serializers.py file code only.

Serializers.py:
from rest_framework import serializers
from myapp.models import Employee
MOHAN S.REDDY

#validators
def starts_with_s(value):
if value[0].lower()!='s':
raise serializers.ValidationError('Name
should starts with letter s')

class EmployeeSerialzer(serializers.Serializer):

name=serializers.CharField(max_length=20,validators
=[starts_with_s])
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()

def create(self, validated_data):


return
Employee.objects.create(**validated_data)

def update(self, instance, validated_data):

instance.name=validated_data.get('name',instance.na
me)
instance.address =
validated_data.get('address', instance.address)
instance.mail = validated_data.get('mail',
instance.mail)
instance.age = validated_data.get('age',
instance.age)
instance.save()
return instance

#field level validation


def validate_age(self,value):
MOHAN S.REDDY

if value>100:
raise serializers.ValidationError("Age
should not exceed 100")
return value

#object level validation


def validate(self, data):
name=data.get('name')
addr=data.get('address')
if name.lower()=="durga" and
addr.lower()!='hyd':
raise
serializers.ValidationError("address should be
hyd")
return data

DRF Model Serializer Class:

 Model serializer class will provide automatic serialize class with fields that
are related to model fields.
 Model serializer class is just model based serializer class.
 It will create automatically set of fields based on the model.
 It will generate validators automatically.
 It will provide default implementation of create and update methods.

Syntax:

from rest_framework import serializers

class StudentSerialzer (serializers.ModelSerializer):

class Meta:

model=Student

fields=['id','name','address','mail','age']
MOHAN S.REDDY

#fields='__all__'

Create a new project and application

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp1',
'rest_framework',
]

models.py :

from django.db import models

# Create your models here.


class Student(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail=models.CharField(max_length=20)
age=models.IntegerField()

admin.py:

from django.contrib import admin


from myapp1.models import Student
# Register your models here.

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
MOHAN S.REDDY

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin

Create a new python file with the name serializers.py.

serializers.py:

from rest_framework import serializers


from myapp1.models import Student

class
StudentSerializer(serializers.ModelSerializer):
# validators
def starts_with_s(value):
if value[0].lower() != 's':
raise serializers.ValidationError('Name
should starts with letter s')
#address=serializers.CharField(read_only=True)

name=serializers.CharField(validators=[starts_with_
s])
class Meta:
model=Student
#fields=['name','address','mail','age']
fields='__all__'
#read_only_fields=['address','age']
MOHAN S.REDDY

views.py:

from django.shortcuts import render


import io
from rest_framework.parsers import JSONParser
from myapp1.serializers import StudentSerializer
from myapp1.models import Student
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse
from django.views.decorators.csrf import
csrf_exempt
from django.utils.decorators import
method_decorator
from django.views import View

# Create your views here.


@method_decorator(csrf_exempt,name='dispatch')
class studentdata(View):
def get(self,request,*args,**kwargs):
if request.method == 'GET':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id', None)
if id is not None:
emp = Student.objects.get(id=id)
serializer = StudentSerializer(emp)
jsondata =
JSONRenderer().render(serializer.data)
return HttpResponse(jsondata,
content_type='application/json')
emp = Student.objects.all()
serializer = StudentSerializer(emp,
many=True)
jsondata =
JSONRenderer().render(serializer.data)
MOHAN S.REDDY

return HttpResponse(jsondata,
content_type='application/json')

def post(self, request, *args, **kwargs):


if request.method == 'POST':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
serializer =
StudentSerializer(data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data inserted
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')

def put(self, request, *args, **kwargs):


if request.method == 'PUT':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = Student.objects.get(id=id)
#
serializer=EmployeeSerialzer(emp,data=py_data,parti
al=True)
serializer = StudentSerializer(emp,
data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data updated
MOHAN S.REDDY

into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')

def delete(self, request, *args, **kwargs):


if request.method == 'DELETE':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = Student.objects.get(id=id)
emp.delete()
result = {'message': 'Data deleted
from database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')

urls.py:

from django.contrib import admin


from django.urls import path
from myapp1 import views

urlpatterns = [
path('admin/', admin.site.urls),
path('student/',views.studentdata.as_view()),
MOHAN S.REDDY

Create a new python file with the name api.py inside the application.

api.py:

import requests
import json

URL="http://127.0.0.1:8000/student/"

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
r=requests.get(url=URL,data=jsondata)
data=r.json()
print(data)

#get_record(1)
#get_record()

def post_record():
data = {
'name': 'sairam',
'address': 'hyd',
'mail': 'sairam@gmail.com',
'age': 26
}
jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)

post_record()
MOHAN S.REDDY

def update_record():
data = {
'id':1,
'name': 'durga',
'address': 'hyd',
'mail':'durga@gmail.com',
'age': 45
}
jsondata=json.dumps(data)
r=requests.put(url=URL,data=jsondata)
data=r.json()
print(data)

#update_record()

def delete_data():
data={'id':4}

jsondata=json.dumps(data)
r=requests.delete(url=URL,data=jsondata)
data=r.json()
print(data)

#delete_data()

 Now start server : python manage.py runserver


 Python api.py( in new terminal window)

DRF api_view:

 api_view allow us to define functions that match standard http methods like
GET, POST, PUT ,PATCH etc.
 The main functionality of api_view decorator is which takes a list of HTTP
methods that your view should respond.
MOHAN S.REDDY

 api_view will simplify the view logic.

resquest.data :

 request. data returns the parsed content of the request body. This is
similar to the standard request. It includes all parsed content.

Response:

 Response objects are initialized with data, which should consist of native
python primitives.

Headers:

 HTTP Headers are an important part of the API request and response as they
represent the meta-data associated with the API request and response.
 Headers carry information for: Request and Response Body

Ex with CRUD api_view using function based view:

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp2',
]

Models.py:

from django.db import models

# Create your models here.


MOHAN S.REDDY

class Trainer(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:

from django.contrib import admin


from myapp2.models import Trainer
# Register your models here.

@admin.register(Trainer)
class TrainerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:
from rest_framework import serializers
from myapp2.models import Trainer
MOHAN S.REDDY

class
TrainerSerializer(serializers.ModelSerializer):
class Meta:
model=Trainer
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from rest_framework.decorators import api_view
from rest_framework.response import Response
from myapp2.models import Trainer
from myapp2.serializers import TrainerSerializer

# Create your views here.


@api_view(['GET','POST','PUT','DELETE'])
def trainer_api(request):
if request.method == 'GET':
id = request.data.get('id')
if id is not None:
tr=Trainer.objects.get(id=id)
serializer=TrainerSerializer(tr)
return Response(serializer.data)
tr=Trainer.objects.all()
serializer=TrainerSerializer(tr,many=True)
return Response(serializer.data)
urls.py :

from django.contrib import admin


from django.urls import path
from myapp2 import views

urlpatterns = [
path('admin/', admin.site.urls),
MOHAN S.REDDY

path('trainer/',views.trainer_api),
]

Create a new python file with the name test.py inside the application.

test.py:

import requests
import json

URL=" http://127.0.0.1:8000/trainer/"

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)

headers={'content-Type':'application/json'}

r=requests.get(url=URL,headers=headers,data=jsondat
a)
data=r.json()
print(data)

#get_record(1)
get_record()

Ex with CRUD api_view using function based view:

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
MOHAN S.REDDY

'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp2',
]

Models.py:
from django.db import models

# Create your models here.


class Trainer(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:
from django.contrib import admin
from myapp2.models import Trainer
# Register your models here.

@admin.register(Trainer)
class TrainerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
MOHAN S.REDDY

 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp2.models import Trainer

class
TrainerSerializer(serializers.ModelSerializer):
class Meta:
model=Trainer
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from rest_framework.decorators import api_view
from rest_framework.response import Response
from myapp2.models import Trainer
from myapp2.serializers import TrainerSerializer

# Create your views here.


@api_view(['GET','POST','PUT','DELETE'])
def trainer_api(request):
if request.method == 'GET':
id = request.data.get('id')
if id is not None:
tr=Trainer.objects.get(id=id)
serializer=TrainerSerializer(tr)
return Response(serializer.data)
tr=Trainer.objects.all()
MOHAN S.REDDY

serializer=TrainerSerializer(tr,many=True)
return Response(serializer.data)

if request.method=='POST':

serializer=TrainerSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
inserted"})
return Response(serializer.errors)

if request.method=='PUT':
id=request.data.get('id')
tr=Trainer.objects.get(pk=id)

serializer=TrainerSerializer(tr,data=request.data,p
artial=True)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
updated"})
return Response(serializer.errors)

if request.method=='DELETE':
id=request.data.get('id')
tr=Trainer.objects.get(pk=id)
tr.delete()
return Response({"message":"Record
deleted"})

urls.py :

from django.contrib import admin


from django.urls import path
from myapp2 import views
MOHAN S.REDDY

urlpatterns = [
path('admin/', admin.site.urls),
path('trainer/',views.trainer_api),
]
Create a new python file with the name test.py inside the application.

test.py:

import requests
import json

URL=" http://127.0.0.1:8000/trainer/"

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)

headers={'content-Type':'application/json'}

r=requests.get(url=URL,headers=headers,data=jsondat
a)
data=r.json()
print(data)

#get_record(1)
#get_record()

def post_record():
data = {
'name': 'sairam',
'address': 'hyd',
'mail': 'sairam@gmail.com',
'age': 26
}
jsondata=json.dumps(data)
MOHAN S.REDDY

headers = {'content-Type': 'application/json'}

r=requests.post(url=URL,headers=headers,data=jsonda
ta)
data=r.json()
print(data)

#post_record()

def update_record():
data = {
'id':1,
'name': 'mohan',
'address': 'srnagar',
'mail':'mohan@gmail.com',
'age': 30
}
jsondata=json.dumps(data)
headers = {'content-Type': 'application/json'}

r=requests.put(url=URL,headers=headers,data=jsondat
a)
data=r.json()
print(data)

#update_record()

def delete_data():
data={'id':4}

jsondata=json.dumps(data)
headers = {'content-Type': 'application/json'}

r=requests.delete(url=URL,headers=headers,data=json
data)
data=r.json()
print(data)
MOHAN S.REDDY

delete_data()

Ex with CRUD APIView using class based view with browser API testing:

 REST framework provides an APIView class, which subclasses Django's


View class.
 APIView classes are different from regular View classes in the following
ways: Requests passed to the handler methods will be REST framework's
Request instances, not Django's HttpRequest instances.

Models.py :

from django.db import models

# Create your models here.


class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:

from django.contrib import admin


from myapp3.models import Manager
# Register your models here.
@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

serializer.py :

from rest_framework import serializers


from myapp3.models import Manager
MOHAN S.REDDY

class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']

views.py :

from django.shortcuts import render


from rest_framework.views import APIView
from myapp3.serializer import ManagerSerializer
from rest_framework.response import Response
from rest_framework import status
from myapp3.models import Manager
# Create your views here.

class ManagerAPI(APIView):
def get(self,request,pk=None,format=None):
id=pk
if id is not None:
m=Manager.objects.get(id=id)
serializer=ManagerSerializer(m)
return Response(serializer.data)
m=Manager.objects.all()
serializer=ManagerSerializer(m,many=True)
return Response(serializer.data)

def post(self,request,format=None):

serializer=ManagerSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({'message':'Data
inserted'},status=status.HTTP_201_CREATED)
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)
MOHAN S.REDDY

def put(self,request,pk,format=None):
id=pk
m=Manager.objects.get(pk=id)

serializer=ManagerSerializer(m,data=request.data)
if serializer.is_valid():
serializer.save()
return Response({'message':"Data is
updated"})
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)

def patch(self,request,pk,format=None):
id=pk
m=Manager.objects.get(pk=id)

serializer=ManagerSerializer(m,data=request.data,pa
rtial=True)
if serializer.is_valid():
serializer.save()
return Response({'message':"partiallly
updated"})
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)

def delete(self,request,pk,format=None):
id=pk
m=Manager.objects.get(pk=id)
m.delete()
return Response({'message':"Record is
deleted"})

urls.py :

from django.contrib import admin


from django.urls import path
MOHAN S.REDDY

from myapp3 import views

urlpatterns = [
path('admin/', admin.site.urls),
path('manager/',views.ManagerAPI.as_view()),

path('manager/<int:pk>',views.ManagerAPI.as_view())
,
]
Note: to test this, go to browser and then type
http://127.0.0.1:8000/manager/

Generic API View and mixins:

 Generic API views are set of commonly used patterns.


 The purpose of Generic API view is to quickly build API views that map
closely to our database models without repeating the code.
 Generic API view is more loaded version of APIView
MOHAN S.REDDY

 mixin: a mixin is a class which contains a combination of methods from


other classes.
 Mixins provides bits of common behavior; they cannot be used standalone
that means we cannot use mixins without Generic API view.
 Mixins must pair with Gneric API view to make a functional view.

Types of mixin:

 CreateModelMixin: Create a model instance


 ListModelMixin: List a queryset
 RetrieveModelMixin : Retrieve a model instance
 UpdateModelMixin: Update a model instance
 DestroyModelMixin: Delete a model instance

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp4',
]

Models.py:

from django.db import models

# Create your models here.


class Customer(models.Model):
name=models.CharField(max_length=20)
MOHAN S.REDDY

address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:

from django.contrib import admin


from myapp4.models import Customer
# Register your models here.
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:
from rest_framework import serializers
from myapp4.models import Customer

class
CustomerSerializer(serializers.ModelSerializer):
class Meta:
model=Customer
fields=['id','name','address','mail','age']
MOHAN S.REDDY

views.py:

from django.shortcuts import render


from myapp4.serializers import CustomerSerializer
from myapp4.models import Customer
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import
ListModelMixin,CreateModelMixin,RetrieveModelMixin,
UpdateModelMixin,DestroyModelMixin

# Create your views here.


class CustomerList(GenericAPIView,ListModelMixin):
queryset = Customer.objects.all()
serializer_class =CustomerSerializer

def get(self,request,*args,**kwargs):
return self.list(request,*args,**kwargs)

class
CustomerCreate(GenericAPIView,CreateModelMixin):
queryset = Customer.objects.all()
serializer_class =CustomerSerializer

def post(self,request,*args,**kwargs):
return self.create(request,*args,**kwargs)

class
CustomerRetrieve(GenericAPIView,RetrieveModelMixin)
:
queryset = Customer.objects.all()
serializer_class =CustomerSerializer

def get(self,request,*args,**kwargs):
return
self.retrieve(request,*args,**kwargs)
MOHAN S.REDDY

class
CustomerUpdate(GenericAPIView,UpdateModelMixin):
queryset = Customer.objects.all()
serializer_class =CustomerSerializer

def put(self,request,*args,**kwargs):
return self.update(request,*args,**kwargs)

class
CustomerDelete(GenericAPIView,DestroyModelMixin):
queryset = Customer.objects.all()
serializer_class =CustomerSerializer

def delete(self,request,*args,**kwargs):
return self.destroy(request,*args,**kwargs)

#Retrieve,Update,Delete
class
Retrive_Update_Delete(GenericAPIView,RetrieveModelM
ixin,UpdateModelMixin,DestroyModelMixin):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

def get(self, request, *args, **kwargs):


return self.retrieve(request, *args,
**kwargs)

def put(self,request,*args,**kwargs):
return self.update(request,*args,**kwargs)

def delete(self, request, *args, **kwargs):


return self.destroy(request, *args,
**kwargs)

#List ,Create
MOHAN S.REDDY

class List_Create(GenericAPIView,ListModelMixin,
CreateModelMixin):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

def get(self, request, *args, **kwargs):


return self.list(request, *args, **kwargs)

def post(self, request, *args, **kwargs):


return self.create(request, *args,
**kwargs)

urls.py :

from django.contrib import admin


from django.urls import path
from myapp4 import views

urlpatterns = [
path('admin/', admin.site.urls),

#path('customerlist/',views.CustomerList.as_view())
,

#path('customercreate/',views.CustomerCreate.as_vie
w()),
#path('customerretrieve/<int:pk>',
views.CustomerRetrieve.as_view()),
#path('customerupdate/<int:pk>',
views.CustomerUpdate.as_view()),
#path('customerdelete/<int:pk>',
views.CustomerDelete.as_view()),

path('RUD/<int:pk>',views.Retrive_Update_Delete.as_
view()),
MOHAN S.REDDY

path('LC/',views.List_Create.as_view()),

Concrete View Classes:

 Concrete views do most of the work that we need to do on our own when
using APIView .
 They use mixins as their basic building blocks, combine the building blocks
with GenericAPIView , and bind actions to the methods.
 The following are the concrete generic views.
1. ListAPIView
2. CreateAPIView
3. RetrieveAPIView
4. UpdateAPIView
5. DestroyAPIView
6. ListCreateAPIView
7. RetrieveUpdateAPIView
8. RetrieveDestroyAPIView
9. RetrieveUpdateDestroyAPIView
MOHAN S.REDDY
MOHAN S.REDDY

All classes that extend from a concrete view require:

 queryset
 serializer class

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
MOHAN S.REDDY

'rest_framework',

'myapp5',
]

Models.py:
from django.db import models

# Create your models here.


class Customer(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:
from django.contrib import admin
from myapp5.models import Customer
# Register your models here.
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records
MOHAN S.REDDY

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp5.models import Customer

class
CustomerSerializer(serializers.ModelSerializer):
class Meta:
model=Customer
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from myapp5.models import Customer
from myapp5.serializers import CustomerSerializer
from rest_framework.generics import ListAPIView,

CreateAPIView,RetrieveAPIView,UpdateAPIView,Destroy
APIView,

ListCreateAPIView,RetrieveUpdateAPIView,RetrieveDes
troyAPIView,RetrieveUpdateDestroyAPIView

# Create your views here.


class CustomerList(ListAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class CustomerCreate(CreateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class CustomerRetrieve(RetrieveAPIView):
MOHAN S.REDDY

queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class CustomerUpdate(UpdateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class CustomerDestroy(DestroyAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class CustomerListCreate(ListCreateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class
CustomerRetrieveUpdate(RetrieveUpdateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class
CustomerRetrieveDestroy(RetrieveDestroyAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

class
CustomerRetrieveUpdateDestroy(RetrieveUpdateDestroy
APIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer

urls.py :

from django.contrib import admin


from django.urls import path
from myapp5 import views
MOHAN S.REDDY

urlpatterns = [
path('admin/', admin.site.urls),

path('customerlist/',views.CustomerList.as_view()),

path('customercreate/',views.CustomerCreate.as_view
()),

path('customerretrieve/<int:pk>',views.CustomerRetr
ieve.as_view()),

path('customerupdate/<int:pk>',views.CustomerUpdate
.as_view()),
path('customerdestroy/<int:pk>',
views.CustomerDestroy.as_view()),

path('customerlistcreate/',views.CustomerListCreate
.as_view()),

path('customerretrieveupdate/<int:pk>',views.Custom
erRetrieveUpdate.as_view()),
path('customerretrievedestroy/<int:pk>',
views.CustomerRetrieveDestroy.as_view()),
path('customerretrieveupdatedestroy/<int:pk>',
views.CustomerRetrieveUpdateDestroy.as_view()),

Working with ViewSet:

 Django REST framework allows you to combine the logic for a set of related
views in a single class, called a ViewSet.
 In other frameworks you may also find conceptually similar
implementations named something like 'Resources' or 'Controllers'.
MOHAN S.REDDY

 A ViewSet class is simply a type of class-based View, that does not provide
any method handlers such as .get() or .post(), and instead provides actions
such as .list() and .create().
 The method handlers for a ViewSet are only bound to the corresponding
actions at the point of finalizing the view, using the .as_view() method.
 Typically, rather than explicitly registering the views in a viewset in the
urlconf, you'll register the viewset with a router class, that automatically
determines the urlconf for you.
 Routers are used with ViewSets in django rest framework to auto config the
urls.
 Routers provides a simple, quick and consistent way of writing ViewSet
logic to a set of URLs.
 Router automatically maps the incoming request to proper viewset action
based on the request method type(i.e GET, POST, etc).

ViewSet attributes:

basename :

 The base to use for the URL names that are created.
 If unset, the basename will be automatically generated based on the queryset
attribute of the viewset.
 Note that if the viewset does not include a queryset attribute then you must
set basename when registering the viewset.

action :

 The name of the current action(list, create)

detail:

 Return Boolean, indicates that the current action is configured for a list or
detail view.

name :

 The display name for the view set.

Settings.py:
MOHAN S.REDDY

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp6',
]

Models.py:

from django.db import models

# Create your models here.


class Customer(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:

from django.contrib import admin


from myapp6.models import Customer
# Register your models here.
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


MOHAN S.REDDY

 Python manage.py migrate


 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp6.models import Customer

class
CustomerSerializer(serializers.ModelSerializer):
class Meta:
model=Customer
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from rest_framework.response import Response
from myapp6.models import Customer
from myapp6.serializers import CustomerSerializer
from rest_framework import status
from rest_framework import viewsets

# Create your views here.


class CustomerViewset(viewsets.ViewSet):
def list(self,request):
print("Basename:",self.basename)
print("Action:",self.action)
print("Detail:",self.detail)
print("Name:",self.name)
MOHAN S.REDDY

cust=Customer.objects.all()

serializer=CustomerSerializer(cust,many=True)
return Response(serializer.data)

def retrieve(selfself,request,pk=None):
id=pk
if id is not None:
cust=Customer.objects.get(id=id)
serializer=CustomerSerializer(cust)
return Response(serializer.data)

def create(self,request):

serializer=CustomerSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
inserted"},status=status.HTTP_201_CREATED)
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)

def update(self,request,pk):
id=pk
cust=Customer.objects.get(pk=id)
serializer =
CustomerSerializer(cust,data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
updated"})
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def partial_update(self,request,pk):
id=pk
cust=Customer.objects.get(pk=id)
MOHAN S.REDDY

serializer =
CustomerSerializer(cust,data=request.data,partial=T
rue)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data is
partially updated"})
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def destroy(selfself,request,pk):
id=pk
cust=Customer.objects.get(pk=id)
cust.delete()
return Response({"message":"Record
deleted"})

urls.py :

from django.contrib import admin


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

#create a router object


router=DefaultRouter()

#register your viewset with router


router.register('CustomerViewset',views.CustomerVie
wset,basename='customer')

urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),

]
MOHAN S.REDDY

Working with ModelViewSet:

 The ModelViewSet class inherits from GenericAPIView and includes


implementations for various actions, by mixing in the behavior of the
various mixin classes.
 The actions provided by the ModelViewSet class are .list(), .retrieve(),
.create(), .update(), .partial_update(), and .destroy().
 Because ModelViewSet extends GenericAPIView, you'll normally need to
provide at least the queryset and serializer_class attributes.

ReadOnlyModelViewSet:

 The ReadOnlyModelViewSet class also inherits from GenericAPIView. As


with ModelViewSet it also includes implementations for various actions, but
unlike ModelViewSet only provides the 'read-only' actions, .list() and
.retrieve()

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp7',
]

Models.py:

from django.db import models

# Create your models here.


MOHAN S.REDDY

class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:

from django.contrib import admin


from myapp7.models import Manager
# Register your models here.
@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp7.models import Manager

class
ManagerSerializer(serializers.ModelSerializer):
MOHAN S.REDDY

class Meta:
model=Manager
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from myapp7.models import Manager
from myapp7.serializers import ManagerSerializer
from rest_framework import viewsets

# Create your views here.


class ManagerModelViewSet(viewsets.ModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer

#ReadOnlyModelViewSet
'''class
ManagerModelViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer'''

urls.py:

from django.contrib import admin


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

#create a router object


router=DefaultRouter()

#register your viewset with router


router.register('ManagerViewset',views.ManagerModel
ViewSet,basename='manager')

urlpatterns = [
MOHAN S.REDDY

path('admin/', admin.site.urls),
path('',include(router.urls)),

Authentication and Permissions in DRF:

 Authentication is the mechanism of associating an incoming request with a


set of identifying credentials, such as the user the request came from, or the
token that it was signed with.
 Authentication is the process of checking the user credentials are correct or
not (username and password).
 REST framework provides several authentication schemes, and also allows
you to implement custom schemes.
 Authentication always runs at the very start of the view, before the
permission checks occur, and before any other code is allowed to proceed.
 Don't forget that authentication by itself won't allow or disallow an
incoming request; it simply identifies the credentials that the request was
made with.

Types of Authentication:

1. Basic Authentication
2. Token Authentication
3. Session Authentication
4. Remote User Authentication
5. Custom Authentication

Permissions:

 Permissions determine whether a request should be granted or denied


access.
 Permission checks are always run at the very start of the view, before any
other code is allowed to proceed. Permission checks will typically use the
authentication information in the request.user and request.auth properties to
determine if the incoming request should be permitted.
MOHAN S.REDDY

 Permissions are used to grant or deny access for different classes of users to
different parts of the API.
 The simplest style of permission would be to allow access to any
authenticated user, and deny access to any unauthenticated user. This
corresponds to the IsAuthenticated class in REST framework.

Permission classes:

 REST Framework will provide list of permission classes


1. AllowAny
2. IsAuthenticated
3. IsAdminUser
4. IsAuthenticatedorReadOnly
5. DjangoModelPermissions
6. DjangoModelPermissionsorAnonReadOnly
7. DjangoObjectPermissions

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp7',
]

Models.py:

from django.db import models

# Create your models here.


MOHAN S.REDDY

class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()
admin.py:

from django.contrib import admin


from myapp7.models import Manager
# Register your models here.
@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp7.models import Manager

class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
MOHAN S.REDDY

model=Manager
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from myapp7.models import Manager
from myapp7.serializers import ManagerSerializer
from rest_framework import viewsets
from rest_framework.authentication import
BasicAuthentication
from rest_framework.permissions import
IsAuthenticated,AllowAny,IsAdminUser

# Create your views here.


class ManagerModelViewSet(viewsets.ModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer
#authentication_classes = [BasicAuthentication]
#permission_classes = [AllowAny]
#permission_classes = [IsAuthenticated]
#permission_classes = [IsAdminUser]

urls.py:

from django.contrib import admin


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

#create a router object


router=DefaultRouter()

#register your viewset with router


router.register('ManagerViewset',views.ManagerModel
ViewSet,basename='manager')
MOHAN S.REDDY

urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),

Note: instead of implement authentication in views.py file we can also use


settings.py file code like below.

settings.py:

REST_FRAMEWORK={

'DEFAULT_AUTHENTICATION_CLASSES':['rest_framework.a
uthentication.BasicAuthentication'],

'DEFAULT_PERMISSION_CLASSES':['rest_framework.permi
ssions.IsAuthenticated']
}

Permission classes:

 REST Framework will provide list of permission classes


8. AllowAny
9. IsAuthenticated
10. IsAdminUser
11. IsAuthenticatedorReadOnly
12. DjangoModelPermissions
13. DjangoModelPermissionsorAnonReadOnly
14. DjangoObjectPermissions

AllowAny :

 Any users can access API

IsAuthenticated:
MOHAN S.REDDY

 Authenticated users only can access API

IsAdminUser :

 Authenticated users and users must have staff status is true.

IsAuthenticatedorReadOnly :

 Authenticated users can access API and Unauthenticated users can only read
but can not write.

DjangoModelPermissions :

 Users should be authenticated and must have enough permissions for read
and write.

DjangoModelPermissionsorAnonReadOnly :

 If user is authenticated, he should have permissions for read and write,


 Id user is not authenticated he can read only.

DjangoObjectPermissions :

 User must be authenticate and user should have enough permission on


particular objects.

Working with SessionAuthentication:

 This authentication scheme uses Django's default session backend for


authentication.
 If successfully authenticated, SessionAuthentication provides the following
credentials.
 request.user will be a Django User instance.
 request.auth will be None.
 Unauthenticated responses that are denied permission will result in an HTTP
403 Forbidden response.

CustomPermissions:
MOHAN S.REDDY

 To implement a custom permission, override BasePermission and implement


either, or both, of the following methods:

.has_permission(self, request, view)

.has_object_permission(self, request, view, obj)

 The methods should return True if the request should be granted access, and
False otherwise.

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp7',
]

Models.py:

from django.db import models

# Create your models here.


class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()
admin.py:

from django.contrib import admin


from myapp7.models import Manager
MOHAN S.REDDY

# Register your models here.


@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp7.models import Manager

class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from myapp7.models import Manager
from myapp7.serializers import ManagerSerializer
from rest_framework import viewsets
MOHAN S.REDDY

from rest_framework.authentication import


SessionAuthentication
from rest_framework.permissions import
IsAuthenticatedOrReadOnly,DjangoModelPermissions,Dj
angoModelPermissionsOrAnonReadOnly

from myapp7.custompermissions import


CustomPermission

# Create your views here.


class ManagerModelViewSet(viewsets.ModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer
authentication_classes =
[SessionAuthentication]
#permission_classes =
[IsAuthenticatedOrReadOnly]
#permission_classes = [DjangoModelPermissions]
#permission_classes =
[DjangoModelPermissionsOrAnonReadOnly]

permission_classes = [CustomPermission]

urls.py:

from django.contrib import admin


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

#create a router object


router=DefaultRouter()

#register your viewset with router


router.register('ManagerViewset',views.ManagerModel
ViewSet,basename='manager')
MOHAN S.REDDY

urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),

path('authentication/',include('rest_framework.urls
',namespace='rest_framework'))

Note: create a new python file with the name custmpermissions.py

custompermissions.py:

from rest_framework.permissions import


BasePermission

class CustomPermission(BasePermission):
def has_permission(self, request, view):
if request.method=='GET':
return True
return False

Working with TokenAuthentication:

 This authentication scheme uses a simple token-based HTTP Authentication


scheme.
 Token authentication is appropriate for client-server setups, such as native
desktop and mobile clients.
 To use the TokenAuthentication scheme you'll need to configure the
authentication classes to include TokenAuthentication, and additionally
include rest_framework.authtoken in your INSTALLED_APPS settings.py
file:

INSTALLED_APPS = [
...
'rest_framework.authtoken'
]
MOHAN S.REDDY

 Note: Make sure to run manage.py migrate after changing your settings. The
rest_framework.authtoken app provides Django database migrations.
 If successfully authenticated, TokenAuthentication provides the following
credentials.
 request.user will be a Django User instance.
 request.auth will be a rest_framework.authtoken.models.Token instance.
 Unauthenticated responses that are denied permission will result in an HTTP
401 Unauthorized response .

Options to generate token :

1. Using Admin Interface


2. Using manage.py command in terminal
3. By exposing API endpoint
4. Using signals

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp8',
'rest_framework.authtoken',

Models.py:
MOHAN S.REDDY

from django.db import models

# Create your models here.


class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()
admin.py:

from django.contrib import admin


from myapp8.models import Manager
# Register your models here.
@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp8.models import Manager

class
MOHAN S.REDDY

ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from myapp8.models import Manager
from myapp8.serializers import ManagerSerializer
from rest_framework import viewsets
from rest_framework.authentication import
TokenAuthentication

# Create your views here.


class ManagerModelViewSet(viewsets.ModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer

urls.py:

from django.contrib import admin


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

#create a router object


router=DefaultRouter()

#register your viewset with router


router.register('ManagerViewset',views.ManagerModel
ViewSet,basename='manager')

urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
MOHAN S.REDDY

path('authentication/',include('rest_framework.urls
',namespace='rest_framework'))

1. Generating a token using admin interface

Note: to generate token using admin interface, first run server


http://127.0.0.1:8000/admin

 Go to admin panel, click on tokens, click on Add token, select user for
creating a token and then click on save.

1. Generating a token using manage.py command

Note: go to terminal and type the following command

 python manage.py drf_create_token mohan

Note: if user has token then it will return that, if user don’t have any token then it
will create a token.

Generate token by exposing API endpoint:

httpie :

 HTTPie (pronounced as aitch-tee-tee-pie) is a command-line HTTP client to


make CLI interaction with web services as human-friendly as possible.
 HTTPie provides a simple http command that allows for sending arbitrary
HTTP requests using a simple and natural syntax and displays beautifully
colorized output.
 To Install httpie, Go to terminal and then type the following command
 pip install httpie

urls.py :
MOHAN S.REDDY

from django.contrib import admin


from django.urls import path,include
from myapp8 import views
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken.views import
obtain_auth_token

#create a router object


router=DefaultRouter()
#register your viewset with router
router.register('ManagerViewset',views.ManagerModel
ViewSet,basename='manager')

urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),

path('authentication/',include('rest_framework.urls
',namespace='rest_framework')),
path('gettoken/',obtain_auth_token)
]

Now go to terminal and then type following command

F:\djangoProject5pm> http http://127.0.0.1:8000/gettoken/ username="shanvi"


password="durgasoft@123"

This will create a token for shanvi user.

Generate token by using signals:

models.py :

from django.db import models


from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
MOHAN S.REDDY

# Create your models here.


class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

@receiver(post_save,sender=settings.AUTH_USER_MODEL
)
def
create_auth_token(sender,instance=None,created=Fals
e,**kwargs):
if created:
Token.objects.create(user=instance)

Note: in this case as soon as we create a user through signal automatically token
will be create.

Ex to test API using token authentication:

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp8',
'rest_framework.authtoken',
MOHAN S.REDDY

Models.py:

from django.db import models


from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

# Create your models here.


class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

@receiver(post_save,sender=settings.AUTH_USER_MODEL
)
def
create_auth_token(sender,instance=None,created=Fals
e,**kwargs):
if created:
Token.objects.create(user=instance)

admin.py:

from django.contrib import admin


from myapp8.models import Manager
# Register your models here.
@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
MOHAN S.REDDY

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp8.models import Manager

class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']

views.py:

from django.shortcuts import render


from myapp8.models import Manager
from myapp8.serializers import ManagerSerializer
from rest_framework import viewsets
from rest_framework.authentication import
TokenAuthentication
from rest_framework.permissions import
IsAuthenticated

# Create your views here.


MOHAN S.REDDY

class ManagerModelViewSet(viewsets.ModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]

urls.py:

from django.contrib import admin


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

#create a router object


router=DefaultRouter()
#register your viewset with router
router.register('ManagerViewset',views.ManagerModel
ViewSet,basename='manager')

urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),

path('authentication/',include('rest_framework.urls
',namespace='rest_framework')),

 Now go to terminal : python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 After login in to admin panel, create a new user and insert few records into a
manager table.
 Now open new terminal and test your API with token authentication by
following commands.

For Reading records:


MOHAN S.REDDY

 http http://127.0.0.1:8000/ManagerViewset/ 'Authorization:Token


a91294fb8b2653427334896a3fccf558e2d701dd'

For POST a record:

 http -f POST http://127.0.0.1:8000/ManagerViewset/ name=kumar


address=hyd mail=kumar@gmail.com age=45 'Authorization:Token
a91294fb8b2653427334896a3fccf558e2d701dd'

For PUT a record:

 http PUT http://127.0.0.1:8000/ManagerViewset/1/ name=manoj


address=hyd mail=manoj@gmail.com age=33 'Authorization:Token
a91294fb8b2653427334896a3fccf558e2d701dd'

For DELETE a record:

 http DELETE http://127.0.0.1:8000/ManagerViewset/2/


'Authorization:Token a91294fb8b2653427334896a3fccf558e2d701dd'

Working with custom authentication:

 To implement a custom authentication scheme, subclass


BaseAuthentication and override the .authenticate (self, request) method.
 The method should return a two-tuple of (user, auth) if authentication
succeeds, or None otherwise.
 In some circumstances instead of returning None, you may want to raise
an AuthenticationFailed exception from the .authenticate () method.
 Typically the approach you should take is:
 If authentication is not attempted, return None. Any other authentication
schemes also in use will still be checked.
 If authentication is attempted but fails, raise an AuthenticationFailed
exception. An error response will be returned immediately, regardless of
any permissions checks, and without checking any other authentication
schemes.
MOHAN S.REDDY

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',

'myapp8',

Models.py:
from django.db import models

# Create your models here.


class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()

admin.py:

from django.contrib import admin


from myapp8.models import Manager
# Register your models here.
@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
MOHAN S.REDDY

list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp8.models import Manager

class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']

Create a new python file with the name authentication.py.

from rest_framework.authentication import


BaseAuthentication
from django.contrib.auth.models import User
from rest_framework.exceptions import
AuthenticationFailed
MOHAN S.REDDY

class CustomAuthentication(BaseAuthentication):
def authenticate(self, request):
username=request.GET.get('username')
if username is None:
return None

try:

user=User.objects.get(username=username)
except User.DoesNotExist:
raise AuthenticationFailed("User does
not exist")
return (user,None)

views.py:
from myapp8.models import Manager
from myapp8.serializers import ManagerSerializer
from rest_framework import viewsets
from rest_framework.permissions import
IsAuthenticated
from myapp8.authentication import
CustomAuthentication

# Create your views here.


class ManagerModelViewSet(viewsets.ModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer
authentication_classes = [CustomAuthentication]
permission_classes = [IsAuthenticated]

urls.py:
MOHAN S.REDDY

from django.contrib import admin


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

#create a router object


router=DefaultRouter()
#register your viewset with router
router.register('ManagerViewset',views.ManagerModel
ViewSet,basename='manager')

urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),

path('authentication/',include('rest_framework.urls
',namespace='rest_framework')),

 Now go to terminal : python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 HTTP 200 OK
 Allow: GET, HEAD, OPTIONS
 Content-Type: application/json
 Vary: Accept

 {
 "ManagerViewset": "http://127.0.0.1:8000/ManagerViewset/"
 }

 Click on the ManagerViewset link and try the below link with providing
username

 http://127.0.0.1:8000/ManagerViewset/?username=mohan

Filtering in DRF:
MOHAN S.REDDY

 The default behavior of REST framework's generic list views is to return


the entire queryset for a model manager. Often you will want your API to
restrict the items that are returned by the queryset.
 The simplest way to filter the queryset of any view that subclasses
GenericAPIView is to override the get_queryset() method.
 Overriding this method allows you to customize the queryset returned by the
view in a number of different ways.

Settings.py :

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]

models.py :

from django.db import models

# Create your models here.


class Student(models.Model):
name=models.CharField(max_length=20)
sid=models.IntegerField()
saddress=models.CharField(max_length=20)
trainedby=models.CharField(max_length=20)

admin.py :

from django.contrib import admin


from myapp.models import Student
# Register your models here.
MOHAN S.REDDY

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display =
['id','name','sid','saddress','trainedby']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records and add few users with the name user1 and user2 with
staff status

Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp.models import Student

class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student

fields=['id','name','sid','saddress','trainedby']

views.py :
MOHAN S.REDDY

from myapp.serializers import StudentSerializer


from rest_framework.generics import ListAPIView
from myapp.models import Student

class StudentList(ListAPIView):
queryset = Student.objects.all()
#queryset =
Student.objects.filter(trainedby="user1")
serializer_class = StudentSerializer

urls.py:

from django.contrib import admin


from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),

path('studentapi/',views.StudentList.as_view()),
]

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin/studentapi/

Filtering against the current user:

 You might want to filter the queryset to ensure that only results relevant to
the currently authenticated user making the request are returned.
 You can do so by filtering based on the value of request.user

Views.py:

from django.shortcuts import render


from myapp.serializers import StudentSerializer
from rest_framework.generics import ListAPIView
from myapp.models import Student

# Create your views here.


MOHAN S.REDDY

class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer

def get_queryset(self):
user=self.request.user
return
Student.objects.filter(trainedby=user)

Generic Filtering:

 As well as being able to override the default queryset, REST framework also
includes support for generic filtering backends that allow you to easily
construct complex searches and filters.
 Generic filters can also present themselves as HTML controls in the
browsable API and admin API.

DjangoFilterBackend:

 The django-filter library includes a DjangoFilterBackend class which


supports highly customizable field filtering for REST framework.
 To use DjangoFilterBackend, first install django-filter.
 pip install django-filter
 Then add 'django_filters' to Django's INSTALLED_APPS:
 INSTALLED_APPS = [
...
'django_filters',
...
]
 You should now either add the filter backend to your settings:

REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS':
['django_filters.rest_framework.DjangoFilterBackend']
}
MOHAN S.REDDY

 Or add the filter backend to an individual View or ViewSet.

Settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'django_filters',
]

REST_FRAMEWORK={

'DEFAULT_FILTER_BACKENDS':['django_filters.rest_fra
mework.DjangoFilterBackend']
}

Views.py:

from django.shortcuts import render


from myapp.serializers import StudentSerializer
from rest_framework.generics import ListAPIView
from myapp.models import Student

# Create your views here.

class StudentList(ListAPIView):
queryset = Student.objects.all()
MOHAN S.REDDY

serializer_class = StudentSerializer
filterset_fields=['saddress']

 Now run server: python manage.py runserver


 Now go to browser:
http://127.0.0.1:8000/admin/studentapi/?saddress=hyderabad

 Now you can remove default filter backends from settings.py file and
try below code .

Views.py:

from myapp.serializers import StudentSerializer


from rest_framework.generics import ListAPIView
from myapp.models import Student
from django_filters.rest_framework import
DjangoFilterBackend

# Create your views here.

class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields=['saddress','trainedby']

 Now run server: python manage.py runserver


 Now go to browser:
http://127.0.0.1:8000/admin/studentapi/?saddress=hyderabad&trainedby=us
er1

Search Filter:
MOHAN S.REDDY

 The SearchFilter class supports simple single query parameter based


searching, and is based on the Django admin's search functionality.
 When in use, the browsable API will include a SearchFilter control.
 The SearchFilter class will only be applied if the view has a search_fields
attribute set.
 The search_fields attribute should be a list of names of text type fields on the
model, such as CharField or TextField

Settings.py :

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'django_filters',

models.py :

from django.db import models

# Create your models here.


class Student(models.Model):
name=models.CharField(max_length=20)
sid=models.IntegerField()
saddress=models.CharField(max_length=20)
trainedby=models.CharField(max_length=20)

admin.py :
MOHAN S.REDDY

from django.contrib import admin


from myapp.models import Student
# Register your models here.

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display =
['id','name','sid','saddress','trainedby']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records
 Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from myapp.models import Student

class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student

fields=['id','name','sid','saddress','trainedby']

views.py :
MOHAN S.REDDY

from django.shortcuts import render


from myapp.serializers import StudentSerializer
from rest_framework.generics import ListAPIView
from myapp.models import Student
from rest_framework.filters import SearchFilter

# Create your views here.

class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [SearchFilter]
search_fields=['saddress']
#search_fields = ['saddress','name']
#search_fields=['^name'] #startswith
#search_fields = ['=name'] #exact match

urls.py:

from django.contrib import admin


from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),

path('studentapi/',views.StudentList.as_view()),
]

 Now run server: python manage.py runserver


 Now go to browser:
http://127.0.0.1:8000/admin/studentapi/?search=hyderabad

 By default, the search parameter is named 'search', but this may be


overridden with the SEARCH_PARAM setting.
 Go to settings.py and write the following code
MOHAN S.REDDY

REST_FRAMEWORK={
#'SEARCH_PARAM':'search' #default
'SEARCH_PARAM':'s'
}
 Now go to browser: http://127.0.0.1:8000/admin/studentapi/?s=hyderabad

Ordering Filter:

 The OrderingFilter class supports simple query parameter controlled


ordering of results.
 By default, the query parameter is named 'ordering', but this may by
overridden with the ORDERING_PARAM setting.

Views.py:

from django.shortcuts import render


from myapp.serializers import StudentSerializer
from rest_framework.generics import ListAPIView
from myapp.models import Student
from rest_framework.filters import OrderingFilter

# Create your views here.


class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [OrderingFilter]
#ordering_fields=['name'] #ascending order
#ordering_fields = ['-name'] #descending order
ordering_fields=['name','saddress'] #multiple
fields ordering

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin/studentapi/?ordering=name
MOHAN S.REDDY

Pagination in DRF:

 Django provides a few classes that help you manage paginated data – that is,
data that’s split across several pages, with “Previous/Next” links.
 REST framework includes support for customizable pagination styles. This
allows you to modify how large result sets are split into individual pages of
data.
 Pagination can be of 3 ways.
1. PageNumberPagination
2. LimitOffsetPagination
3. CursorPagination

Setting pagination style:

 The pagination style may be set globally, using the


DEFAULT_PAGINATION_CLASS and PAGE_SIZE

Working with PageNumberPagination:

Settings.py:

REST_FRAMEWORK={
'DEFAULT_PAGINATION_CLASS':'rest_framework.paginati
on.PageNumberPagination',
'PAGE_SIZE':3
}
 You can also set the pagination class on an individual view by using the
pagination_class attribute.

Settings.py :

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
MOHAN S.REDDY

'myapp.apps.MyappConfig',
'rest_framework',
'paginationapp',
]

models.py :

from django.db import models

# Create your models here.


class Student(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
age=models.IntegerField()

admin.py :

from django.contrib import admin


from paginationapp.models import Student
# Register your models here.
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display = ['id','name','address','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records
 Create a new python file with the name serializers.py.

serializer.py:
MOHAN S.REDDY

from rest_framework import serializers


from paginationapp.models import Student

class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
fields=['id','name','address','age']

views.py :

from django.shortcuts import render


from paginationapp.serializers import
StudentSerializer
from paginationapp.models import Student
from rest_framework.generics import ListAPIView

# Create your views here.


class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer

urls.py:

from django.contrib import admin


from django.urls import path
from paginationapp import views

urlpatterns = [
path('admin/', admin.site.urls),

path('studentapi/',views.StudentList.as_view()),
]
MOHAN S.REDDY

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin/studentapi/

Pagination per view:

 Create a new python file with the name pagination.py

Pagination.py:

from rest_framework.pagination import


PageNumberPagination

class MyPagination(PageNumberPagination):
page_size = 3
page_query_param = 'p'
page_size_query_param = 'records'
max_page_size = 5

views.py :

from django.shortcuts import render


from paginationapp.serializers import
StudentSerializer
from paginationapp.models import Student
from rest_framework.generics import ListAPIView
from paginationapp.pagination import MyPagination

# Create your views here.


class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
pagination_class = MyPagination

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin/studentapi/
MOHAN S.REDDY

 http://127.0.0.1:8000/studentapi/?page=2
 http://127.0.0.1:8000/studentapi/?p=2

Working with LimitOffsetPagination:

 This pagination style mirrors the syntax used when looking up multiple
database records. The client includes both a "limit" and an "offset" query
parameter.
 The limit indicates the maximum number of items to return, and is
equivalent to the page_size in other styles. The offset indicates the starting
position of the query in relation to the complete set of unpaginated items.
 To set this globally write the following code in settings.py

REST_FRAMEWORK={

'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.LimitOffs
etPagination'
}

Settings.py :

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'paginationapp',
]

models.py :
MOHAN S.REDDY

from django.db import models

# Create your models here.


class Student(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
age=models.IntegerField()

admin.py :

from django.contrib import admin


from paginationapp.models import Student
# Register your models here.
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display = ['id','name','address','age']

Now go to terminal and then type the following commands

 Python manage.py makemigrations


 Python manage.py migrate
 Python manage.py createsuperuser

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin
 Insert few records
 Create a new python file with the name serializers.py.

serializer.py:

from rest_framework import serializers


from paginationapp.models import Student

class
StudentSerializer(serializers.ModelSerializer):
class Meta:
MOHAN S.REDDY

model=Student
fields=['id','name','address','age']

views.py :

from django.shortcuts import render


from paginationapp.serializers import
StudentSerializer
from paginationapp.models import Student
from rest_framework.generics import ListAPIView

# Create your views here.


class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer

urls.py:

from django.contrib import admin


from django.urls import path
from paginationapp import views

urlpatterns = [
path('admin/', admin.site.urls),

path('studentapi/',views.StudentList.as_view()),
]

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin/studentapi/
MOHAN S.REDDY

Pagination.py:

from rest_framework.pagination import


LimitOffsetPagination

class MyPagination(LimitOffsetPagination):
default_limit = 5
limit_query_param = 'pagelimit'
offset_query_param = 'pageoffset'
max_limit = 4

views.py :

from django.shortcuts import render


from paginationapp.serializers import
StudentSerializer
from paginationapp.models import Student
from rest_framework.generics import ListAPIView
from paginationapp.pagination import MyPagination

# Create your views here.


class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
pagination_class = MyPagination

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin/studentapi/
 http://127.0.0.1:8000/studentapi/?limit=4&offset=7

Working with CursorPagination:

 This pagination style only presents forward and reverse controls, and does
not allow the client to navigate to arbitrary positions.
 Cursor based pagination requires that there is a unique, unchanging ordering
of items in the result set.
MOHAN S.REDDY

 This ordering might typically be a creation timestamp on the records, as this


presents a consistent ordering to paginate against.
 Cursor based pagination is more complex than other schemes. It also
requires that the result set presents a fixed ordering, and does not allow the
client to arbitrarily index into the result set. However it does provide the
following benefits:
 Provides a consistent pagination view. When used properly
CursorPagination ensures that the client will never see the same item twice
when paging through records, even when new items are being inserted by
other clients during the pagination process.

Pagination.py:

from rest_framework.pagination import


CursorPagination

class MyPagination(CursorPagination):
page_size = 3
ordering = 'name'
cursor_query_param = 'c'

Working with Hyperlink Model Serializer:

 The HyperlinkedModelSerializer class is similar to the ModelSerializer


class except that it uses hyperlinks to represent relationships, rather than
primary keys.
 By default the serializer will include a url field instead of a primary key
field.
 The url field will be represented using a HyperlinkedIdentityField
serializer field, and any relationships on the model will be represented
using a HyperlinkedRelatedField serializer field.

Models.py:

from django.db import models

# Create your models here.


MOHAN S.REDDY

class Student(models.Model):
name=models.CharField(max_length=20)
sid=models.IntegerField()
saddress=models.CharField(max_length=20)

admin.py:

from django.contrib import admin


from myapp1.models import Student
# Register your models here.

@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display = ['id','name','sid','saddress']

serializers.py:

from rest_framework import serializers


from myapp1.models import Student

class
StudentSerializer(serializers.HyperlinkedModelSeria
lizer):
class Meta:
model=Student
fields=['id','url','name','sid','saddress']

views.py:

from django.shortcuts import render


from myapp1.serializers import StudentSerializer
from myapp1.models import Student
from rest_framework import viewsets

# Create your views here.


class StudentModelViewset(viewsets.ModelViewSet):
MOHAN S.REDDY

queryset = Student.objects.all()
serializer_class = StudentSerializer

urls.py:

from django.contrib import admin


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

router=DefaultRouter()

router.register('studentapi',views.StudentModelView
set,basename='student')
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
]

 Now run server: python manage.py runserver


 Now go to browser: http://127.0.0.1:8000/admin/studentapi/

Throttling in DRF:

 API throttling allows you to control the way an API is used.


 API throttling is the process of limiting the number of API requests a user
can make in a certain period.
 Throttling is similar to permissions, in that it determines if a request should
be authorized.
 Throttles indicate a temporary state, and are used to control the rate of
requests that clients can make to an API.
 The Django REST Framework has three throttling classes in the
rest_framework.throttling module.
MOHAN S.REDDY

 AnonRate, UserRate, and ScopedRate throttle. All these classes specify


throttling rules that signify the maximum number of requests in a given time
within the scope.

Ex:

 Create a new application with the name throttleapp

settings.py:

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'throttleapp',

]
models.py:

from django.db import models

# Create your models here.


class Student(models.Model):
name=models.CharField(max_length=20)
sid=models.IntegerField()
saddress=models.CharField(max_length=20)

admin.py :

from django.contrib import admin


from throttleapp.models import Student
# Register your models here.

@admin.register(Student)
MOHAN S.REDDY

class StudentAdmin(admin.ModelAdmin):
list_display = ['id','name','sid','saddress']

 Now make migrations and migrate

serializers.py:

from rest_framework import serializers


from throttleapp.models import Student

class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
fields=['id','url','name','sid','saddress']

views.py:

from rest_framework.permissions import


IsAuthenticatedOrReadOnly
from rest_framework.authentication import
SessionAuthentication
from rest_framework.throttling import
AnonRateThrottle,UserRateThrottle

# Create your views here.


class StudentModelViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
authentication_classes =
[SessionAuthentication]
permission_classes =
[IsAuthenticatedOrReadOnly]
throttle_classes = [AnonRateThrottle,
UserRateThrottle]
MOHAN S.REDDY

urls.py:

from django.contrib import admin


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

router=DefaultRouter()

router.register('studentapi',views.StudentModelView
Set,basename='student')
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),

path('auth/',include('rest_framework.urls',namespac
e='rest_framework'))
]

settings.py:

REST_FRAMEWORK={
'DEFAULT_THROTTLE_RATES':{
'anon':'3/day',
'user':'4/hour',

}
}

Now run server : python manage.py runserver

Note: non authenticated user can make 3 requests per day and authenticated user
can make 4 requests per hour.

 Create a new python file with the name throttling.py

throttling.py :
MOHAN S.REDDY

from rest_framework.throttling import


UserRateThrottle

class MohanRateThrottle(UserRateThrottle):
scope='Mohan'

views.py :

from rest_framework.permissions import


IsAuthenticatedOrReadOnly
from rest_framework.authentication import
SessionAuthentication
from rest_framework.throttling import
AnonRateThrottle,UserRateThrottle
from throttleapp.throttling import
MohanRateThrottle

# Create your views here.


class StudentModelViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
authentication_classes =
[SessionAuthentication]
permission_classes =
[IsAuthenticatedOrReadOnly]
#throttle_classes =
[AnonRateThrottle,UserRateThrottle]
throttle_classes = [AnonRateThrottle,
MohanRateThrottle]

settings.py :

REST_FRAMEWORK={
'DEFAULT_THROTTLE_RATES':{
'anon':'3/day',
'user':'4/hour',
'Mohan':'2/minute'
MOHAN S.REDDY

}
}

Note: to do throttling settings in global, use the following code in settings.py


file.

REST_FRAMEWORK={

'DEFAULT_THROTTLE_CLASSES':[

'rest_framework.throttling.AnonRateThrottle',

'rest_framework.throttling.UserRateThrottle'

],

'DEFAULT_THROTTLE_RATES':{

'anon':'100/day',

'user':'1000/day'

You might also like