0% found this document useful (0 votes)
317 views122 pages

Rest Api

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
317 views122 pages

Rest Api

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link]

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 [Link]

 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 [Link]

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 [Link] startapp Restapp
 Open Restproject in pycharm editor
 Install Restapp under [Link]

[Link]:
MOHAN [Link]

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'Restapp',
'rest_framework',
]

[Link]:

from [Link] import models

# Create your models here.


class Employees([Link]):
empid=[Link]()
ename=[Link](max_length=20)
eaddress=[Link](max_length=20)
email=[Link](max_length=30)

def __str__(self):
return [Link]

[Link] :

from [Link] import admin


from [Link] import Employees

# Register your models here.


[Link](Employees)

Now go to terminal and then type the following commands

 Python [Link] makemigrations


MOHAN [Link]

 Python [Link] migrate


 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 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 [Link]

[Link]:

from rest_framework import serializers


from [Link] import Employees

class empSerializer([Link]):

class Meta:
model=Employees
fields='__all__'

[Link]:

from rest_framework.views import APIView


from rest_framework.response import Response
from [Link] import Employees
from [Link] import empSerializer

# Create your views here.


class empDetails(APIView):

def get(self,request):
emp=[Link]()
serializer=empSerializer(emp,many=True)
MOHAN [Link]

return Response([Link])

def post(self):
pass

[Link]:

from [Link] import admin


from [Link] import path
from Restapp import views

urlpatterns = [
path('admin/', [Link]),
path('emp/',[Link].as_view()),
]

 Now run server: python [Link] runserver


 Now go to browser: [Link]

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 [Link]

 Go to [Link]

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
]

[Link]:
from [Link] import models

# Create your models here.


class Employee([Link]):
ename=[Link](max_length=20)
eaddress=[Link](max_length=20)
email=[Link](max_length=20)

[Link]:
from [Link] import admin
from [Link] import Employee

# Register your models here.


@[Link](Employee)
class EmployeeAdmin([Link]):
list_display =['id','ename','eaddress','email']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


MOHAN [Link]

 Python [Link] migrate


 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Now go to admin panel by login with super user login id and password
and insert few records.

[Link]:

from rest_framework import serializers

class EmpSerializer([Link]):
id=[Link](max_length=20)
ename=[Link](max_length=20)
eaddress=[Link](max_length=20)
email=[Link](max_length=20)

[Link]:
from [Link] import Employee
from [Link] import EmpSerializer
from rest_framework.renderers import JSONRenderer
from [Link] import HttpResponse

# Create your views here.

def emp_details(request,pk):
emp=[Link](id=pk)
#print(emp)
serializer=EmpSerializer(emp)
#print(serializer)

json_data=JSONRenderer().render([Link])
#print(json_data)
return
HttpResponse(json_data,content_type='application/js
MOHAN [Link]

on')

def emp_all_details(request):
emp=[Link]()
serializer=EmpSerializer(emp,many=True)

json_data=JSONRenderer().render([Link])
return
HttpResponse(json_data,content_type='application/js
on')

[Link] :

from [Link] import admin


from [Link] import path
from myapp import views

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

Note: create a new python file with the name [Link]

[Link] :

import requests

URL="[Link]
r=[Link](url=URL)
emp_data=[Link]()
print(emp_data)

 Go to terminal and run [Link]


 python [Link]
MOHAN [Link]

Note: from [Link] 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 [Link]

 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. [Link] 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.

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
MOHAN [Link]

'[Link]',
]

[Link]:

from [Link] import models

# Create your models here.


class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()

[Link]:

from [Link] import admin


from [Link] import Manager
# Register your models here.

@[Link](Manager)
class ManagerAdmin([Link]):
list_display = ['name','address','mail','age']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
MOHAN [Link]

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Manager

class ManagerSerialzer([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()

def create(self, validated_data):


return
[Link](**validated_data)

[Link]:

from [Link] import render


import io
from rest_framework.parsers import JSONParser
from [Link] import ManagerSerialzer
from rest_framework.renderers import JSONRenderer
from [Link] import HttpResponse
from [Link] import
csrf_exempt

# Create your views here.


@csrf_exempt
def create_Manager(request):
if [Link]=='POST':
jsondata=[Link]
MOHAN [Link]

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

jsondata=JSONRenderer().render([Link])
return HttpResponse(jsondata,
content_type='application/json')

[Link]:

from [Link] import admin


from [Link] import path
from myapp import views

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

Create a new python file with the name [Link] inside the application.

[Link]:

import requests
import json

URL="[Link]
MOHAN [Link]

data={
'name':'mohan',
'address':'hyderabad',
'mail':'mohan@[Link]',
'age':37
}

jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

 Now start server : python [Link] runserver


 Python [Link]( 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

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
]

[Link] :
MOHAN [Link]

from [Link] import models

# Create your models here.


class Employee([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()

[Link]:

from [Link] import admin


from [Link] import Employee
# Register your models here.

@[Link](Employee)
class EmployeeAdmin([Link]):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]

Create a new python file with the name [Link].

[Link]:
from rest_framework import serializers
from [Link] import Employee
MOHAN [Link]

class EmployeeSerialzer([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()

def create(self, validated_data):


return
[Link](**validated_data)

def update(self, instance, validated_data):

[Link]=validated_data.get('name',[Link]
me)
[Link] =
validated_data.get('address', [Link])
[Link] = validated_data.get('mail',
[Link])
[Link] = validated_data.get('age',
[Link])
[Link]()
return instance

[Link]:

from [Link] import render


import io
from rest_framework.parsers import JSONParser
from [Link] import EmployeeSerialzer
from [Link] import Employee
from rest_framework.renderers import JSONRenderer
from [Link] import HttpResponse
from [Link] import
csrf_exempt
MOHAN [Link]

# Create your views here.


@csrf_exempt
def emp_data(request):
if [Link]=='GET':
jsondata=[Link]
stream=[Link](jsondata)
py_data=JSONParser().parse(stream)
id=py_data.get('id',None)
if id is not None:
emp=[Link](id=id)
serializer=EmployeeSerialzer(emp)

jsondata=JSONRenderer().render([Link])
return
HttpResponse(jsondata,content_type='application/jso
n')

emp=[Link]()
serializer =
EmployeeSerialzer(emp,many=True)
jsondata =
JSONRenderer().render([Link])
return HttpResponse(jsondata,
content_type='application/json')

if [Link] == 'POST':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
serializer =
EmployeeSerialzer(data=py_data)
if serializer.is_valid():
[Link]()
result = {'message': 'Data inserted
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
MOHAN [Link]

content_type='application/json')
jsondata =
JSONRenderer().render([Link])
return HttpResponse(jsondata,
content_type='application/json')

if [Link]=='PUT':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
id=py_data.get('id')
emp=[Link](id=id)

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

if [Link]=='DELETE':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = [Link](id=id)
[Link]()
MOHAN [Link]

result = {'message': 'Data deleted from


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

[Link]:

from [Link] import admin


from [Link] import path
from myapp import views

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

Create a new python file with the name [Link] inside the application.

[Link]:

import requests
import json

URL="[Link]

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#get_record(1)
#get_record()
MOHAN [Link]

def post_record():
data = {
'name': 'kiran',
'address': 'vizag',
'mail': 'kiran@[Link]',
'age': 28
}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#post_record()

def update_record():
data = {
'id':1,
'name': 'ramesh',
'address': 'vizag',
'mail':'ramesh@[Link]',
'age': 45
}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#update_record()

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

jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)
MOHAN [Link]

delete_data()

 Now start server : python [Link] runserver


 Python [Link]( 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

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
]

[Link] :

from [Link] import models

# Create your models here.


class Employee([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()
MOHAN [Link]

[Link]:

from [Link] import admin


from [Link] import Employee
# Register your models here.

@[Link](Employee)
class EmployeeAdmin([Link]):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Employee

class EmployeeSerialzer([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()

def create(self, validated_data):


return
[Link](**validated_data)
MOHAN [Link]

def update(self, instance, validated_data):

[Link]=validated_data.get('name',[Link]
me)
[Link] =
validated_data.get('address', [Link])
[Link] = validated_data.get('mail',
[Link])
[Link] = validated_data.get('age',
[Link])
[Link]()
return instance

[Link]:

from [Link] import render


import io
from rest_framework.parsers import JSONParser
from [Link] import EmployeeSerialzer
from [Link] import Employee
from rest_framework.renderers import JSONRenderer
from [Link] import HttpResponse
from [Link] import
csrf_exempt
from [Link] import
method_decorator
from [Link] import View

# Create your views here.


@method_decorator(csrf_exempt,name='dispatch')
class empdata(View):
def get(self,request,*args,**kwargs):
if [Link] == 'GET':
jsondata = [Link]
stream = [Link](jsondata)
MOHAN [Link]

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

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


if [Link] == 'POST':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
serializer =
EmployeeSerialzer(data=py_data)
if serializer.is_valid():
[Link]()
result = {'message': 'Data inserted
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render([Link])
return HttpResponse(jsondata,
content_type='application/json')

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


MOHAN [Link]

if [Link] == 'PUT':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = [Link](id=id)
#
serializer=EmployeeSerialzer(emp,data=py_data,parti
al=True)
serializer = EmployeeSerialzer(emp,
data=py_data)
if serializer.is_valid():
[Link]()
result = {'message': 'Data updated
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render([Link])
return HttpResponse(jsondata,
content_type='application/json')

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


if [Link] == 'DELETE':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = [Link](id=id)
[Link]()
result = {'message': 'Data deleted
from database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
MOHAN [Link]

[Link]:

from [Link] import admin


from [Link] import path
from myapp import views

urlpatterns = [
path('admin/', [Link]),
path('emp/',[Link].as_view()),

Create a new python file with the name [Link] inside the application.

[Link]:

import requests
import json

URL="[Link]

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#get_record(1)
#get_record()

def post_record():
data = {
MOHAN [Link]

'name': 'kiran',
'address': 'vizag',
'mail': 'kiran@[Link]',
'age': 28
}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#post_record()

def update_record():
data = {
'id':1,
'name': 'ramesh',
'address': 'vizag',
'mail':'ramesh@[Link]',
'age': 45
}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#update_record()

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

jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

delete_data()
MOHAN [Link]

 Now start server : python [Link] runserver


 Python [Link]( 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 [Link] file code only.

[Link]:
from rest_framework import serializers
from [Link] import Employee
MOHAN [Link]

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

class EmployeeSerialzer([Link]):

name=[Link](max_length=20,validators
=[starts_with_s])
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()

def create(self, validated_data):


return
[Link](**validated_data)

def update(self, instance, validated_data):

[Link]=validated_data.get('name',[Link]
me)
[Link] =
validated_data.get('address', [Link])
[Link] = validated_data.get('mail',
[Link])
[Link] = validated_data.get('age',
[Link])
[Link]()
return instance

#field level validation


def validate_age(self,value):
MOHAN [Link]

if value>100:
raise [Link]("Age
should not exceed 100")
return value

#object level validation


def validate(self, data):
name=[Link]('name')
addr=[Link]('address')
if [Link]()=="durga" and
[Link]()!='hyd':
raise
[Link]("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 ([Link]):

class Meta:

model=Student

fields=['id','name','address','mail','age']
MOHAN [Link]

#fields='__all__'

Create a new project and application

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'myapp1',
'rest_framework',
]

[Link] :

from [Link] import models

# Create your models here.


class Student([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail=[Link](max_length=20)
age=[Link]()

[Link]:

from [Link] import admin


from [Link] import Student
# Register your models here.

@[Link](Student)
class StudentAdmin([Link]):
list_display =
['id','name','address','mail','age']
MOHAN [Link]

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Student

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

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

[Link]:

from [Link] import render


import io
from rest_framework.parsers import JSONParser
from [Link] import StudentSerializer
from [Link] import Student
from rest_framework.renderers import JSONRenderer
from [Link] import HttpResponse
from [Link] import
csrf_exempt
from [Link] import
method_decorator
from [Link] import View

# Create your views here.


@method_decorator(csrf_exempt,name='dispatch')
class studentdata(View):
def get(self,request,*args,**kwargs):
if [Link] == 'GET':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id', None)
if id is not None:
emp = [Link](id=id)
serializer = StudentSerializer(emp)
jsondata =
JSONRenderer().render([Link])
return HttpResponse(jsondata,
content_type='application/json')
emp = [Link]()
serializer = StudentSerializer(emp,
many=True)
jsondata =
JSONRenderer().render([Link])
MOHAN [Link]

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

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


if [Link] == 'POST':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
serializer =
StudentSerializer(data=py_data)
if serializer.is_valid():
[Link]()
result = {'message': 'Data inserted
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render([Link])
return HttpResponse(jsondata,
content_type='application/json')

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


if [Link] == 'PUT':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = [Link](id=id)
#
serializer=EmployeeSerialzer(emp,data=py_data,parti
al=True)
serializer = StudentSerializer(emp,
data=py_data)
if serializer.is_valid():
[Link]()
result = {'message': 'Data updated
MOHAN [Link]

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

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


if [Link] == 'DELETE':
jsondata = [Link]
stream = [Link](jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = [Link](id=id)
[Link]()
result = {'message': 'Data deleted
from database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')

[Link]:

from [Link] import admin


from [Link] import path
from myapp1 import views

urlpatterns = [
path('admin/', [Link]),
path('student/',[Link].as_view()),
MOHAN [Link]

Create a new python file with the name [Link] inside the application.

[Link]:

import requests
import json

URL="[Link]

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#get_record(1)
#get_record()

def post_record():
data = {
'name': 'sairam',
'address': 'hyd',
'mail': 'sairam@[Link]',
'age': 26
}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

post_record()
MOHAN [Link]

def update_record():
data = {
'id':1,
'name': 'durga',
'address': 'hyd',
'mail':'durga@[Link]',
'age': 45
}
jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#update_record()

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

jsondata=[Link](data)
r=[Link](url=URL,data=jsondata)
data=[Link]()
print(data)

#delete_data()

 Now start server : python [Link] runserver


 Python [Link]( 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 [Link]

 api_view will simplify the view logic.

[Link] :

 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:

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp2',
]

[Link]:

from [Link] import models

# Create your models here.


MOHAN [Link]

class Trainer([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

[Link]:

from [Link] import admin


from [Link] import Trainer
# Register your models here.

@[Link](Trainer)
class TrainerAdmin([Link]):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:
from rest_framework import serializers
from [Link] import Trainer
MOHAN [Link]

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

[Link]:

from [Link] import render


from rest_framework.decorators import api_view
from rest_framework.response import Response
from [Link] import Trainer
from [Link] import TrainerSerializer

# Create your views here.


@api_view(['GET','POST','PUT','DELETE'])
def trainer_api(request):
if [Link] == 'GET':
id = [Link]('id')
if id is not None:
tr=[Link](id=id)
serializer=TrainerSerializer(tr)
return Response([Link])
tr=[Link]()
serializer=TrainerSerializer(tr,many=True)
return Response([Link])
[Link] :

from [Link] import admin


from [Link] import path
from myapp2 import views

urlpatterns = [
path('admin/', [Link]),
MOHAN [Link]

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

Create a new python file with the name [Link] inside the application.

[Link]:

import requests
import json

URL=" [Link]

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=[Link](data)

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

r=[Link](url=URL,headers=headers,data=jsondat
a)
data=[Link]()
print(data)

#get_record(1)
get_record()

Ex with CRUD api_view using function based view:

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
MOHAN [Link]

'[Link]',
'[Link]',
'rest_framework',

'myapp2',
]

[Link]:
from [Link] import models

# Create your models here.


class Trainer([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

[Link]:
from [Link] import admin
from [Link] import Trainer
# Register your models here.

@[Link](Trainer)
class TrainerAdmin([Link]):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
MOHAN [Link]

 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Trainer

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

[Link]:

from [Link] import render


from rest_framework.decorators import api_view
from rest_framework.response import Response
from [Link] import Trainer
from [Link] import TrainerSerializer

# Create your views here.


@api_view(['GET','POST','PUT','DELETE'])
def trainer_api(request):
if [Link] == 'GET':
id = [Link]('id')
if id is not None:
tr=[Link](id=id)
serializer=TrainerSerializer(tr)
return Response([Link])
tr=[Link]()
MOHAN [Link]

serializer=TrainerSerializer(tr,many=True)
return Response([Link])

if [Link]=='POST':

serializer=TrainerSerializer(data=[Link])
if serializer.is_valid():
[Link]()
return Response({"message":"Data
inserted"})
return Response([Link])

if [Link]=='PUT':
id=[Link]('id')
tr=[Link](pk=id)

serializer=TrainerSerializer(tr,data=[Link],p
artial=True)
if serializer.is_valid():
[Link]()
return Response({"message":"Data
updated"})
return Response([Link])

if [Link]=='DELETE':
id=[Link]('id')
tr=[Link](pk=id)
[Link]()
return Response({"message":"Record
deleted"})

[Link] :

from [Link] import admin


from [Link] import path
from myapp2 import views
MOHAN [Link]

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

[Link]:

import requests
import json

URL=" [Link]

def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=[Link](data)

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

r=[Link](url=URL,headers=headers,data=jsondat
a)
data=[Link]()
print(data)

#get_record(1)
#get_record()

def post_record():
data = {
'name': 'sairam',
'address': 'hyd',
'mail': 'sairam@[Link]',
'age': 26
}
jsondata=[Link](data)
MOHAN [Link]

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

r=[Link](url=URL,headers=headers,data=jsonda
ta)
data=[Link]()
print(data)

#post_record()

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

r=[Link](url=URL,headers=headers,data=jsondat
a)
data=[Link]()
print(data)

#update_record()

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

jsondata=[Link](data)
headers = {'content-Type': 'application/json'}

r=[Link](url=URL,headers=headers,data=json
data)
data=[Link]()
print(data)
MOHAN [Link]

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.

[Link] :

from [Link] import models

# Create your models here.


class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

[Link]:

from [Link] import admin


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

[Link] :

from rest_framework import serializers


from [Link] import Manager
MOHAN [Link]

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

[Link] :

from [Link] import render


from rest_framework.views import APIView
from [Link] import ManagerSerializer
from rest_framework.response import Response
from rest_framework import status
from [Link] 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=[Link](id=id)
serializer=ManagerSerializer(m)
return Response([Link])
m=[Link]()
serializer=ManagerSerializer(m,many=True)
return Response([Link])

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

serializer=ManagerSerializer(data=[Link])
if serializer.is_valid():
[Link]()
return Response({'message':'Data
inserted'},status=status.HTTP_201_CREATED)
return
Response([Link],status=status.HTTP_400_B
AD_REQUEST)
MOHAN [Link]

def put(self,request,pk,format=None):
id=pk
m=[Link](pk=id)

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

def patch(self,request,pk,format=None):
id=pk
m=[Link](pk=id)

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

def delete(self,request,pk,format=None):
id=pk
m=[Link](pk=id)
[Link]()
return Response({'message':"Record is
deleted"})

[Link] :

from [Link] import admin


from [Link] import path
MOHAN [Link]

from myapp3 import views

urlpatterns = [
path('admin/', [Link]),
path('manager/',[Link].as_view()),

path('manager/<int:pk>',[Link].as_view())
,
]
Note: to test this, go to browser and then type
[Link]

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 [Link]

 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

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp4',
]

[Link]:

from [Link] import models

# Create your models here.


class Customer([Link]):
name=[Link](max_length=20)
MOHAN [Link]

address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

[Link]:

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:
from rest_framework import serializers
from [Link] import Customer

class
CustomerSerializer([Link]):
class Meta:
model=Customer
fields=['id','name','address','mail','age']
MOHAN [Link]

[Link]:

from [Link] import render


from [Link] import CustomerSerializer
from [Link] 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 = [Link]()
serializer_class =CustomerSerializer

def get(self,request,*args,**kwargs):
return [Link](request,*args,**kwargs)

class
CustomerCreate(GenericAPIView,CreateModelMixin):
queryset = [Link]()
serializer_class =CustomerSerializer

def post(self,request,*args,**kwargs):
return [Link](request,*args,**kwargs)

class
CustomerRetrieve(GenericAPIView,RetrieveModelMixin)
:
queryset = [Link]()
serializer_class =CustomerSerializer

def get(self,request,*args,**kwargs):
return
[Link](request,*args,**kwargs)
MOHAN [Link]

class
CustomerUpdate(GenericAPIView,UpdateModelMixin):
queryset = [Link]()
serializer_class =CustomerSerializer

def put(self,request,*args,**kwargs):
return [Link](request,*args,**kwargs)

class
CustomerDelete(GenericAPIView,DestroyModelMixin):
queryset = [Link]()
serializer_class =CustomerSerializer

def delete(self,request,*args,**kwargs):
return [Link](request,*args,**kwargs)

#Retrieve,Update,Delete
class
Retrive_Update_Delete(GenericAPIView,RetrieveModelM
ixin,UpdateModelMixin,DestroyModelMixin):
queryset = [Link]()
serializer_class = CustomerSerializer

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


return [Link](request, *args,
**kwargs)

def put(self,request,*args,**kwargs):
return [Link](request,*args,**kwargs)

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


return [Link](request, *args,
**kwargs)

#List ,Create
MOHAN [Link]

class List_Create(GenericAPIView,ListModelMixin,
CreateModelMixin):
queryset = [Link]()
serializer_class = CustomerSerializer

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


return [Link](request, *args, **kwargs)

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


return [Link](request, *args,
**kwargs)

[Link] :

from [Link] import admin


from [Link] import path
from myapp4 import views

urlpatterns = [
path('admin/', [Link]),

#path('customerlist/',[Link].as_view())
,

#path('customercreate/',[Link].as_vie
w()),
#path('customerretrieve/<int:pk>',
[Link].as_view()),
#path('customerupdate/<int:pk>',
[Link].as_view()),
#path('customerdelete/<int:pk>',
[Link].as_view()),

path('RUD/<int:pk>',views.Retrive_Update_Delete.as_
view()),
MOHAN [Link]

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 [Link]
MOHAN [Link]

All classes that extend from a concrete view require:

 queryset
 serializer class

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
MOHAN [Link]

'rest_framework',

'myapp5',
]

[Link]:
from [Link] import models

# Create your models here.


class Customer([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records
MOHAN [Link]

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Customer

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

[Link]:

from [Link] import render


from [Link] import Customer
from [Link] 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 = [Link]()
serializer_class = CustomerSerializer

class CustomerCreate(CreateAPIView):
queryset = [Link]()
serializer_class = CustomerSerializer

class CustomerRetrieve(RetrieveAPIView):
MOHAN [Link]

queryset = [Link]()
serializer_class = CustomerSerializer

class CustomerUpdate(UpdateAPIView):
queryset = [Link]()
serializer_class = CustomerSerializer

class CustomerDestroy(DestroyAPIView):
queryset = [Link]()
serializer_class = CustomerSerializer

class CustomerListCreate(ListCreateAPIView):
queryset = [Link]()
serializer_class = CustomerSerializer

class
CustomerRetrieveUpdate(RetrieveUpdateAPIView):
queryset = [Link]()
serializer_class = CustomerSerializer

class
CustomerRetrieveDestroy(RetrieveDestroyAPIView):
queryset = [Link]()
serializer_class = CustomerSerializer

class
CustomerRetrieveUpdateDestroy(RetrieveUpdateDestroy
APIView):
queryset = [Link]()
serializer_class = CustomerSerializer

[Link] :

from [Link] import admin


from [Link] import path
from myapp5 import views
MOHAN [Link]

urlpatterns = [
path('admin/', [Link]),

path('customerlist/',[Link].as_view()),

path('customercreate/',[Link].as_view
()),

path('customerretrieve/<int:pk>',[Link]
ieve.as_view()),

path('customerupdate/<int:pk>',[Link]
.as_view()),
path('customerdestroy/<int:pk>',
[Link].as_view()),

path('customerlistcreate/',[Link]
.as_view()),

path('customerretrieveupdate/<int:pk>',[Link]
erRetrieveUpdate.as_view()),
path('customerretrievedestroy/<int:pk>',
[Link].as_view()),
path('customerretrieveupdatedestroy/<int:pk>',
[Link].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 [Link]

 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.

[Link]:
MOHAN [Link]

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp6',
]

[Link]:

from [Link] import models

# Create your models here.


class Customer([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

[Link]:

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


MOHAN [Link]

 Python [Link] migrate


 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Customer

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

[Link]:

from [Link] import render


from rest_framework.response import Response
from [Link] import Customer
from [Link] import CustomerSerializer
from rest_framework import status
from rest_framework import viewsets

# Create your views here.


class CustomerViewset([Link]):
def list(self,request):
print("Basename:",[Link])
print("Action:",[Link])
print("Detail:",[Link])
print("Name:",[Link])
MOHAN [Link]

cust=[Link]()

serializer=CustomerSerializer(cust,many=True)
return Response([Link])

def retrieve(selfself,request,pk=None):
id=pk
if id is not None:
cust=[Link](id=id)
serializer=CustomerSerializer(cust)
return Response([Link])

def create(self,request):

serializer=CustomerSerializer(data=[Link])
if serializer.is_valid():
[Link]()
return Response({"message":"Data
inserted"},status=status.HTTP_201_CREATED)
return
Response([Link],status=status.HTTP_400_B
AD_REQUEST)

def update(self,request,pk):
id=pk
cust=[Link](pk=id)
serializer =
CustomerSerializer(cust,data=[Link])
if serializer.is_valid():
[Link]()
return Response({"message":"Data
updated"})
return Response([Link],
status=status.HTTP_400_BAD_REQUEST)

def partial_update(self,request,pk):
id=pk
cust=[Link](pk=id)
MOHAN [Link]

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

def destroy(selfself,request,pk):
id=pk
cust=[Link](pk=id)
[Link]()
return Response({"message":"Record
deleted"})

[Link] :

from [Link] import admin


from [Link] import path,include
from myapp6 import views
from rest_framework.routers import DefaultRouter

#create a router object


router=DefaultRouter()

#register your viewset with router


[Link]('CustomerViewset',[Link]
wset,basename='customer')

urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),

]
MOHAN [Link]

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

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp7',
]

[Link]:

from [Link] import models

# Create your models here.


MOHAN [Link]

class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

[Link]:

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Manager

class
ManagerSerializer([Link]):
MOHAN [Link]

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

[Link]:

from [Link] import render


from [Link] import Manager
from [Link] import ManagerSerializer
from rest_framework import viewsets

# Create your views here.


class ManagerModelViewSet([Link]):
queryset = [Link]()
serializer_class = ManagerSerializer

#ReadOnlyModelViewSet
'''class
ManagerModelViewSet([Link]):
queryset = [Link]()
serializer_class = ManagerSerializer'''

[Link]:

from [Link] import admin


from [Link] import path,include
from myapp7 import views
from rest_framework.routers import DefaultRouter

#create a router object


router=DefaultRouter()

#register your viewset with router


[Link]('ManagerViewset',[Link]
ViewSet,basename='manager')

urlpatterns = [
MOHAN [Link]

path('admin/', [Link]),
path('',include([Link])),

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 [Link] and [Link] properties to
determine if the incoming request should be permitted.
MOHAN [Link]

 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

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp7',
]

[Link]:

from [Link] import models

# Create your models here.


MOHAN [Link]

class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()
[Link]:

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Manager

class
ManagerSerializer([Link]):
class Meta:
MOHAN [Link]

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

[Link]:

from [Link] import render


from [Link] import Manager
from [Link] 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([Link]):
queryset = [Link]()
serializer_class = ManagerSerializer
#authentication_classes = [BasicAuthentication]
#permission_classes = [AllowAny]
#permission_classes = [IsAuthenticated]
#permission_classes = [IsAdminUser]

[Link]:

from [Link] import admin


from [Link] import path,include
from myapp7 import views
from rest_framework.routers import DefaultRouter

#create a router object


router=DefaultRouter()

#register your viewset with router


[Link]('ManagerViewset',[Link]
ViewSet,basename='manager')
MOHAN [Link]

urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),

Note: instead of implement authentication in [Link] file we can also use


[Link] file code like below.

[Link]:

REST_FRAMEWORK={

'DEFAULT_AUTHENTICATION_CLASSES':['rest_framework.a
[Link]'],

'DEFAULT_PERMISSION_CLASSES':['rest_framework.permi
[Link]']
}

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 [Link]

 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.
 [Link] will be a Django User instance.
 [Link] will be None.
 Unauthenticated responses that are denied permission will result in an HTTP
403 Forbidden response.

CustomPermissions:
MOHAN [Link]

 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.

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp7',
]

[Link]:

from [Link] import models

# Create your models here.


class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()
[Link]:

from [Link] import admin


from [Link] import Manager
MOHAN [Link]

# Register your models here.


@[Link](Manager)
class ManagerAdmin([Link]):
list_display =
['id','name','address','mail','age']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Manager

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

[Link]:

from [Link] import render


from [Link] import Manager
from [Link] import ManagerSerializer
from rest_framework import viewsets
MOHAN [Link]

from rest_framework.authentication import


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

from [Link] import


CustomPermission

# Create your views here.


class ManagerModelViewSet([Link]):
queryset = [Link]()
serializer_class = ManagerSerializer
authentication_classes =
[SessionAuthentication]
#permission_classes =
[IsAuthenticatedOrReadOnly]
#permission_classes = [DjangoModelPermissions]
#permission_classes =
[DjangoModelPermissionsOrAnonReadOnly]

permission_classes = [CustomPermission]

[Link]:

from [Link] import admin


from [Link] import path,include
from myapp7 import views
from rest_framework.routers import DefaultRouter

#create a router object


router=DefaultRouter()

#register your viewset with router


[Link]('ManagerViewset',[Link]
ViewSet,basename='manager')
MOHAN [Link]

urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),

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

Note: create a new python file with the name [Link]

[Link]:

from rest_framework.permissions import


BasePermission

class CustomPermission(BasePermission):
def has_permission(self, request, view):
if [Link]=='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 [Link]
file:

INSTALLED_APPS = [
...
'rest_framework.authtoken'
]
MOHAN [Link]

 Note: Make sure to run [Link] migrate after changing your settings. The
rest_framework.authtoken app provides Django database migrations.
 If successfully authenticated, TokenAuthentication provides the following
credentials.
 [Link] will be a Django User instance.
 [Link] will be a rest_framework.[Link] 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 [Link] command in terminal
3. By exposing API endpoint
4. Using signals

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp8',
'rest_framework.authtoken',

[Link]:
MOHAN [Link]

from [Link] import models

# Create your models here.


class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()
[Link]:

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Manager

class
MOHAN [Link]

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

[Link]:

from [Link] import render


from [Link] import Manager
from [Link] import ManagerSerializer
from rest_framework import viewsets
from rest_framework.authentication import
TokenAuthentication

# Create your views here.


class ManagerModelViewSet([Link]):
queryset = [Link]()
serializer_class = ManagerSerializer

[Link]:

from [Link] import admin


from [Link] import path,include
from myapp8 import views
from rest_framework.routers import DefaultRouter

#create a router object


router=DefaultRouter()

#register your viewset with router


[Link]('ManagerViewset',[Link]
ViewSet,basename='manager')

urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),
MOHAN [Link]

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


[Link]

 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 [Link] command

Note: go to terminal and type the following command

 python [Link] 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

[Link] :
MOHAN [Link]

from [Link] import admin


from [Link] import path,include
from myapp8 import views
from rest_framework.routers import DefaultRouter
from rest_framework.[Link] import
obtain_auth_token

#create a router object


router=DefaultRouter()
#register your viewset with router
[Link]('ManagerViewset',[Link]
ViewSet,basename='manager')

urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),

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 [Link] username="shanvi"


password="durgasoft@123"

This will create a token for shanvi user.

Generate token by using signals:

[Link] :

from [Link] import models


from [Link] import settings
from [Link] import post_save
from [Link] import receiver
from rest_framework.[Link] import Token
MOHAN [Link]

# Create your models here.


class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

@receiver(post_save,sender=settings.AUTH_USER_MODEL
)
def
create_auth_token(sender,instance=None,created=Fals
e,**kwargs):
if created:
[Link](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:

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp8',
'rest_framework.authtoken',
MOHAN [Link]

[Link]:

from [Link] import models


from [Link] import settings
from [Link] import post_save
from [Link] import receiver
from rest_framework.[Link] import Token

# Create your models here.


class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

@receiver(post_save,sender=settings.AUTH_USER_MODEL
)
def
create_auth_token(sender,instance=None,created=Fals
e,**kwargs):
if created:
[Link](user=instance)

[Link]:

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Manager

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

[Link]:

from [Link] import render


from [Link] import Manager
from [Link] import ManagerSerializer
from rest_framework import viewsets
from rest_framework.authentication import
TokenAuthentication
from rest_framework.permissions import
IsAuthenticated

# Create your views here.


MOHAN [Link]

class ManagerModelViewSet([Link]):
queryset = [Link]()
serializer_class = ManagerSerializer
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]

[Link]:

from [Link] import admin


from [Link] import path,include
from myapp8 import views
from rest_framework.routers import DefaultRouter

#create a router object


router=DefaultRouter()
#register your viewset with router
[Link]('ManagerViewset',[Link]
ViewSet,basename='manager')

urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),

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

 Now go to terminal : python [Link] runserver


 Now go to browser: [Link]
 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 [Link]

 http [Link] 'Authorization:Token


a91294fb8b2653427334896a3fccf558e2d701dd'

For POST a record:

 http -f POST [Link] name=kumar


address=hyd mail=kumar@[Link] age=45 'Authorization:Token
a91294fb8b2653427334896a3fccf558e2d701dd'

For PUT a record:

 http PUT [Link] name=manoj


address=hyd mail=manoj@[Link] age=33 'Authorization:Token
a91294fb8b2653427334896a3fccf558e2d701dd'

For DELETE a record:

 http DELETE [Link]


'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 [Link]

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',

'myapp8',

[Link]:
from [Link] import models

# Create your models here.


class Manager([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
mail = [Link](max_length=20)
age = [Link]()

[Link]:

from [Link] import admin


from [Link] import Manager
# Register your models here.
@[Link](Manager)
class ManagerAdmin([Link]):
MOHAN [Link]

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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Manager

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

Create a new python file with the name [Link].

from rest_framework.authentication import


BaseAuthentication
from [Link] import User
from rest_framework.exceptions import
AuthenticationFailed
MOHAN [Link]

class CustomAuthentication(BaseAuthentication):
def authenticate(self, request):
username=[Link]('username')
if username is None:
return None

try:

user=[Link](username=username)
except [Link]:
raise AuthenticationFailed("User does
not exist")
return (user,None)

[Link]:
from [Link] import Manager
from [Link] import ManagerSerializer
from rest_framework import viewsets
from rest_framework.permissions import
IsAuthenticated
from [Link] import
CustomAuthentication

# Create your views here.


class ManagerModelViewSet([Link]):
queryset = [Link]()
serializer_class = ManagerSerializer
authentication_classes = [CustomAuthentication]
permission_classes = [IsAuthenticated]

[Link]:
MOHAN [Link]

from [Link] import admin


from [Link] import path,include
from myapp8 import views
from rest_framework.routers import DefaultRouter

#create a router object


router=DefaultRouter()
#register your viewset with router
[Link]('ManagerViewset',[Link]
ViewSet,basename='manager')

urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),

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

 Now go to terminal : python [Link] runserver


 Now go to browser: [Link]
 HTTP 200 OK
 Allow: GET, HEAD, OPTIONS
 Content-Type: application/json
 Vary: Accept

 {
 "ManagerViewset": "[Link]
 }

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

 [Link]

Filtering in DRF:
MOHAN [Link]

 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.

[Link] :

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
]

[Link] :

from [Link] import models

# Create your models here.


class Student([Link]):
name=[Link](max_length=20)
sid=[Link]()
saddress=[Link](max_length=20)
trainedby=[Link](max_length=20)

[Link] :

from [Link] import admin


from [Link] import Student
# Register your models here.
MOHAN [Link]

@[Link](Student)
class StudentAdmin([Link]):
list_display =
['id','name','sid','saddress','trainedby']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records and add few users with the name user1 and user2 with
staff status

Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Student

class
StudentSerializer([Link]):
class Meta:
model=Student

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

[Link] :
MOHAN [Link]

from [Link] import StudentSerializer


from rest_framework.generics import ListAPIView
from [Link] import Student

class StudentList(ListAPIView):
queryset = [Link]()
#queryset =
[Link](trainedby="user1")
serializer_class = StudentSerializer

[Link]:

from [Link] import admin


from [Link] import path
from myapp import views

urlpatterns = [
path('admin/', [Link]),

path('studentapi/',[Link].as_view()),
]

 Now run server: python [Link] runserver


 Now go to browser: [Link]

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 [Link]

[Link]:

from [Link] import render


from [Link] import StudentSerializer
from rest_framework.generics import ListAPIView
from [Link] import Student

# Create your views here.


MOHAN [Link]

class StudentList(ListAPIView):
queryset = [Link]()
serializer_class = StudentSerializer

def get_queryset(self):
user=[Link]
return
[Link](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 [Link]

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

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
'django_filters',
]

REST_FRAMEWORK={

'DEFAULT_FILTER_BACKENDS':['django_filters.rest_fra
[Link]']
}

[Link]:

from [Link] import render


from [Link] import StudentSerializer
from rest_framework.generics import ListAPIView
from [Link] import Student

# Create your views here.

class StudentList(ListAPIView):
queryset = [Link]()
MOHAN [Link]

serializer_class = StudentSerializer
filterset_fields=['saddress']

 Now run server: python [Link] runserver


 Now go to browser:
[Link]

 Now you can remove default filter backends from [Link] file and
try below code .

[Link]:

from [Link] import StudentSerializer


from rest_framework.generics import ListAPIView
from [Link] import Student
from django_filters.rest_framework import
DjangoFilterBackend

# Create your views here.

class StudentList(ListAPIView):
queryset = [Link]()
serializer_class = StudentSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields=['saddress','trainedby']

 Now run server: python [Link] runserver


 Now go to browser:
[Link]
er1

Search Filter:
MOHAN [Link]

 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

[Link] :

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
'django_filters',

[Link] :

from [Link] import models

# Create your models here.


class Student([Link]):
name=[Link](max_length=20)
sid=[Link]()
saddress=[Link](max_length=20)
trainedby=[Link](max_length=20)

[Link] :
MOHAN [Link]

from [Link] import admin


from [Link] import Student
# Register your models here.

@[Link](Student)
class StudentAdmin([Link]):
list_display =
['id','name','sid','saddress','trainedby']

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records
 Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Student

class
StudentSerializer([Link]):
class Meta:
model=Student

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

[Link] :
MOHAN [Link]

from [Link] import render


from [Link] import StudentSerializer
from rest_framework.generics import ListAPIView
from [Link] import Student
from rest_framework.filters import SearchFilter

# Create your views here.

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

[Link]:

from [Link] import admin


from [Link] import path
from myapp import views

urlpatterns = [
path('admin/', [Link]),

path('studentapi/',[Link].as_view()),
]

 Now run server: python [Link] runserver


 Now go to browser:
[Link]

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


overridden with the SEARCH_PARAM setting.
 Go to [Link] and write the following code
MOHAN [Link]

REST_FRAMEWORK={
#'SEARCH_PARAM':'search' #default
'SEARCH_PARAM':'s'
}
 Now go to browser: [Link]

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.

[Link]:

from [Link] import render


from [Link] import StudentSerializer
from rest_framework.generics import ListAPIView
from [Link] import Student
from rest_framework.filters import OrderingFilter

# Create your views here.


class StudentList(ListAPIView):
queryset = [Link]()
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 [Link] runserver


 Now go to browser: [Link]
MOHAN [Link]

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:

[Link]:

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

[Link] :

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
MOHAN [Link]

'[Link]',
'rest_framework',
'paginationapp',
]

[Link] :

from [Link] import models

# Create your models here.


class Student([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
age=[Link]()

[Link] :

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records
 Create a new python file with the name [Link].

[Link]:
MOHAN [Link]

from rest_framework import serializers


from [Link] import Student

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

[Link] :

from [Link] import render


from [Link] import
StudentSerializer
from [Link] import Student
from rest_framework.generics import ListAPIView

# Create your views here.


class StudentList(ListAPIView):
queryset = [Link]()
serializer_class = StudentSerializer

[Link]:

from [Link] import admin


from [Link] import path
from paginationapp import views

urlpatterns = [
path('admin/', [Link]),

path('studentapi/',[Link].as_view()),
]
MOHAN [Link]

 Now run server: python [Link] runserver


 Now go to browser: [Link]

Pagination per view:

 Create a new python file with the name [Link]

[Link]:

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

[Link] :

from [Link] import render


from [Link] import
StudentSerializer
from [Link] import Student
from rest_framework.generics import ListAPIView
from [Link] import MyPagination

# Create your views here.


class StudentList(ListAPIView):
queryset = [Link]()
serializer_class = StudentSerializer
pagination_class = MyPagination

 Now run server: python [Link] runserver


 Now go to browser: [Link]
MOHAN [Link]

 [Link]
 [Link]

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 [Link]

REST_FRAMEWORK={

'DEFAULT_PAGINATION_CLASS':'rest_framework.[Link]
etPagination'
}

[Link] :

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
'paginationapp',
]

[Link] :
MOHAN [Link]

from [Link] import models

# Create your models here.


class Student([Link]):
name=[Link](max_length=20)
address=[Link](max_length=20)
age=[Link]()

[Link] :

from [Link] import admin


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

Now go to terminal and then type the following commands

 Python [Link] makemigrations


 Python [Link] migrate
 Python [Link] createsuperuser

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 Insert few records
 Create a new python file with the name [Link].

[Link]:

from rest_framework import serializers


from [Link] import Student

class
StudentSerializer([Link]):
class Meta:
MOHAN [Link]

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

[Link] :

from [Link] import render


from [Link] import
StudentSerializer
from [Link] import Student
from rest_framework.generics import ListAPIView

# Create your views here.


class StudentList(ListAPIView):
queryset = [Link]()
serializer_class = StudentSerializer

[Link]:

from [Link] import admin


from [Link] import path
from paginationapp import views

urlpatterns = [
path('admin/', [Link]),

path('studentapi/',[Link].as_view()),
]

 Now run server: python [Link] runserver


 Now go to browser: [Link]
MOHAN [Link]

[Link]:

from rest_framework.pagination import


LimitOffsetPagination

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

[Link] :

from [Link] import render


from [Link] import
StudentSerializer
from [Link] import Student
from rest_framework.generics import ListAPIView
from [Link] import MyPagination

# Create your views here.


class StudentList(ListAPIView):
queryset = [Link]()
serializer_class = StudentSerializer
pagination_class = MyPagination

 Now run server: python [Link] runserver


 Now go to browser: [Link]
 [Link]

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 [Link]

 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.

[Link]:

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.

[Link]:

from [Link] import models

# Create your models here.


MOHAN [Link]

class Student([Link]):
name=[Link](max_length=20)
sid=[Link]()
saddress=[Link](max_length=20)

[Link]:

from [Link] import admin


from [Link] import Student
# Register your models here.

@[Link](Student)
class StudentAdmin([Link]):
list_display = ['id','name','sid','saddress']

[Link]:

from rest_framework import serializers


from [Link] import Student

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

[Link]:

from [Link] import render


from [Link] import StudentSerializer
from [Link] import Student
from rest_framework import viewsets

# Create your views here.


class StudentModelViewset([Link]):
MOHAN [Link]

queryset = [Link]()
serializer_class = StudentSerializer

[Link]:

from [Link] import admin


from [Link] import path,include
from myapp1 import views
from rest_framework.routers import DefaultRouter

router=DefaultRouter()

[Link]('studentapi',[Link]
set,basename='student')
urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),
]

 Now run server: python [Link] runserver


 Now go to browser: [Link]

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 [Link]

 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

[Link]:

INSTALLED_APPS = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'rest_framework',
'throttleapp',

]
[Link]:

from [Link] import models

# Create your models here.


class Student([Link]):
name=[Link](max_length=20)
sid=[Link]()
saddress=[Link](max_length=20)

[Link] :

from [Link] import admin


from [Link] import Student
# Register your models here.

@[Link](Student)
MOHAN [Link]

class StudentAdmin([Link]):
list_display = ['id','name','sid','saddress']

 Now make migrations and migrate

[Link]:

from rest_framework import serializers


from [Link] import Student

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

[Link]:

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([Link]):
queryset = [Link]()
serializer_class = StudentSerializer
authentication_classes =
[SessionAuthentication]
permission_classes =
[IsAuthenticatedOrReadOnly]
throttle_classes = [AnonRateThrottle,
UserRateThrottle]
MOHAN [Link]

[Link]:

from [Link] import admin


from [Link] import path,include
from throttleapp import views
from rest_framework.routers import DefaultRouter

router=DefaultRouter()

[Link]('studentapi',[Link]
Set,basename='student')
urlpatterns = [
path('admin/', [Link]),
path('',include([Link])),

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

[Link]:

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

}
}

Now run server : python [Link] 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 [Link]

[Link] :
MOHAN [Link]

from rest_framework.throttling import


UserRateThrottle

class MohanRateThrottle(UserRateThrottle):
scope='Mohan'

[Link] :

from rest_framework.permissions import


IsAuthenticatedOrReadOnly
from rest_framework.authentication import
SessionAuthentication
from rest_framework.throttling import
AnonRateThrottle,UserRateThrottle
from [Link] import
MohanRateThrottle

# Create your views here.


class StudentModelViewSet([Link]):
queryset = [Link]()
serializer_class = StudentSerializer
authentication_classes =
[SessionAuthentication]
permission_classes =
[IsAuthenticatedOrReadOnly]
#throttle_classes =
[AnonRateThrottle,UserRateThrottle]
throttle_classes = [AnonRateThrottle,
MohanRateThrottle]

[Link] :

REST_FRAMEWORK={
'DEFAULT_THROTTLE_RATES':{
'anon':'3/day',
'user':'4/hour',
'Mohan':'2/minute'
MOHAN [Link]

}
}

Note: to do throttling settings in global, use the following code in [Link]


file.

REST_FRAMEWORK={

'DEFAULT_THROTTLE_CLASSES':[

'rest_framework.[Link]',

'rest_framework.[Link]'

],

'DEFAULT_THROTTLE_RATES':{

'anon':'100/day',

'user':'1000/day'

You might also like