Rest Api
Rest Api
REDDY
Advantages of DRF:
DRF allows the flexibility to extend and customize the framework’s tools
according to programmer’s demands that greatly reduces development time.
It also provides the support of testing, debugging and caching.
Simplicity, flexibility, quality, and test coverage of source code.
Powerful serialization engine compatible with both ORM and non-ORM
data sources.
Pluggable and easy to customize validators and authenticators.
Generic classes for CRUD operations.
Clean, simple, views for Resources, using Django's new class based views.
MOHAN S.REDDY
API types:
REST API:
REST API is an architectural style for an application programming interface
(API) that uses HTTP request to access and use data.
When web services use REST architecture, they are called Restful APIs or
REST APIs.
A REST API is a set of web addresses that respond with pure information.
API returns JSON or XML, which is common format.
MOHAN S.REDDY
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:
API Resource:
MOHAN S.REDDY
Installing DRF:
INSTALLED_APPS=[
‘rest_framework’
]
Creating API:
Settings.py:
MOHAN S.REDDY
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'Restapp',
'rest_framework',
]
models.py:
def __str__(self):
return self.ename
admin.py :
Note: to convert model data into JSON format then we use serializers.
Add a new python file under the app with the name serializers.py
serializers.py:
class empSerializer(serializers.ModelSerializer):
class Meta:
model=Employees
fields='__all__'
views.py:
def get(self,request):
emp=Employees.objects.all()
serializer=empSerializer(emp,many=True)
MOHAN S.REDDY
return Response(serializer.data)
def post(self):
pass
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('emp/',views.empDetails.as_view()),
]
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:
Go to settings.py
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]
models.py:
from django.db import models
admin.py:
from django.contrib import admin
from myapp.models import Employee
serializers.py:
class EmpSerializer(serializers.Serializer):
id=serializers.CharField(max_length=20)
ename=serializers.CharField(max_length=20)
eaddress=serializers.CharField(max_length=20)
email=serializers.CharField(max_length=20)
views.py:
from myapp.models import Employee
from myapp.serializers import EmpSerializer
from rest_framework.renderers import JSONRenderer
from django.http import HttpResponse
def emp_details(request,pk):
emp=Employee.objects.get(id=pk)
#print(emp)
serializer=EmpSerializer(emp)
#print(serializer)
json_data=JSONRenderer().render(serializer.data)
#print(json_data)
return
HttpResponse(json_data,content_type='application/js
MOHAN S.REDDY
on')
def emp_all_details(request):
emp=Employee.objects.all()
serializer=EmpSerializer(emp,many=True)
json_data=JSONRenderer().render(serializer.data)
return
HttpResponse(json_data,content_type='application/js
on')
urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('emp/<int:pk>',views.emp_details),
path('empall/',views.emp_all_details),
]
test.py :
import requests
URL="http://127.0.0.1:8000/emp/1"
r=requests.get(url=URL)
emp_data=r.json()
print(emp_data)
Note: from test.py file we are requesting to api to get employee data and api will
send request to django application.
De serialization:
The io module provides Python's main facilities for dealing with various
types of I/O.
Python IO module allows us to manage the file-related input and output
operations.
A stream is basically a sequence of data. Whatever data we use in our
programming it flows through a stream.
MOHAN S.REDDY
It parses the incoming request JSON content into python content type dict.
JSONParser. Parses JSON request content. Request.data will be
populated with a dictionary of data.
Data parsing is the process of taking data in one format and
transforming it to another format.
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
MOHAN S.REDDY
'myapp.apps.MyappConfig',
]
models.py:
admin.py:
@admin.register(Manager)
class ManagerAdmin(admin.ModelAdmin):
list_display = ['name','address','mail','age']
serializers.py:
class ManagerSerialzer(serializers.Serializer):
name=serializers.CharField(max_length=20)
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()
views.py:
stream=io.BytesIO(jsondata)
py_data=JSONParser().parse(stream)
serializer=ManagerSerialzer(data=py_data)
if serializer.is_valid():
serializer.save()
result={'message':'Data inserted into
database'}
jsondata=JSONRenderer().render(result)
return
HttpResponse(jsondata,content_type='application/jso
n')
jsondata=JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('createmanager/',views.create_Manager),
]
Create a new python file with the name test.py inside the application.
test.py:
import requests
import json
URL="http://127.0.0.1:8000/createmanager/"
MOHAN S.REDDY
data={
'name':'mohan',
'address':'hyderabad',
'mail':'[email protected]',
'age':37
}
jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]
models.py :
MOHAN S.REDDY
admin.py:
@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
serializers.py:
from rest_framework import serializers
from myapp.models import Employee
MOHAN S.REDDY
class EmployeeSerialzer(serializers.Serializer):
name=serializers.CharField(max_length=20)
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()
instance.name=validated_data.get('name',instance.na
me)
instance.address =
validated_data.get('address', instance.address)
instance.mail = validated_data.get('mail',
instance.mail)
instance.age = validated_data.get('age',
instance.age)
instance.save()
return instance
views.py:
jsondata=JSONRenderer().render(serializer.data)
return
HttpResponse(jsondata,content_type='application/jso
n')
emp=Employee.objects.all()
serializer =
EmployeeSerialzer(emp,many=True)
jsondata =
JSONRenderer().render(serializer.data)
return HttpResponse(jsondata,
content_type='application/json')
if request.method == 'POST':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
serializer =
EmployeeSerialzer(data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data inserted
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
MOHAN S.REDDY
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')
if request.method=='PUT':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id=py_data.get('id')
emp=Employee.objects.get(id=id)
#serializer=EmployeeSerialzer(emp,data=py_data,part
ial=True)
serializer = EmployeeSerialzer(emp,
data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data updated
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')
if request.method=='DELETE':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = Employee.objects.get(id=id)
emp.delete()
MOHAN S.REDDY
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('emp/',views.employee_data),
]
Create a new python file with the name test.py inside the application.
test.py:
import requests
import json
URL="http://127.0.0.1:8000/emp/"
def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
r=requests.get(url=URL,data=jsondata)
data=r.json()
print(data)
#get_record(1)
#get_record()
MOHAN S.REDDY
def post_record():
data = {
'name': 'kiran',
'address': 'vizag',
'mail': '[email protected]',
'age': 28
}
jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)
#post_record()
def update_record():
data = {
'id':1,
'name': 'ramesh',
'address': 'vizag',
'mail':'[email protected]',
'age': 45
}
jsondata=json.dumps(data)
r=requests.put(url=URL,data=jsondata)
data=r.json()
print(data)
#update_record()
def delete_data():
data={'id':2}
jsondata=json.dumps(data)
r=requests.delete(url=URL,data=jsondata)
data=r.json()
print(data)
MOHAN S.REDDY
delete_data()
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]
models.py :
admin.py:
@admin.register(Employee)
class EmployeeAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
serializers.py:
class EmployeeSerialzer(serializers.Serializer):
name=serializers.CharField(max_length=20)
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()
instance.name=validated_data.get('name',instance.na
me)
instance.address =
validated_data.get('address', instance.address)
instance.mail = validated_data.get('mail',
instance.mail)
instance.age = validated_data.get('age',
instance.age)
instance.save()
return instance
views.py:
py_data = JSONParser().parse(stream)
id = py_data.get('id', None)
if id is not None:
emp = Employee.objects.get(id=id)
serializer = EmployeeSerialzer(emp)
jsondata =
JSONRenderer().render(serializer.data)
return HttpResponse(jsondata,
content_type='application/json')
emp = Employee.objects.all()
serializer = EmployeeSerialzer(emp,
many=True)
jsondata =
JSONRenderer().render(serializer.data)
return HttpResponse(jsondata,
content_type='application/json')
if request.method == 'PUT':
jsondata = request.body
stream = io.BytesIO(jsondata)
py_data = JSONParser().parse(stream)
id = py_data.get('id')
emp = Employee.objects.get(id=id)
#
serializer=EmployeeSerialzer(emp,data=py_data,parti
al=True)
serializer = EmployeeSerialzer(emp,
data=py_data)
if serializer.is_valid():
serializer.save()
result = {'message': 'Data updated
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('emp/',views.empdata.as_view()),
Create a new python file with the name test.py inside the application.
test.py:
import requests
import json
URL="http://127.0.0.1:8000/emp/"
def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
r=requests.get(url=URL,data=jsondata)
data=r.json()
print(data)
#get_record(1)
#get_record()
def post_record():
data = {
MOHAN S.REDDY
'name': 'kiran',
'address': 'vizag',
'mail': '[email protected]',
'age': 28
}
jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)
#post_record()
def update_record():
data = {
'id':1,
'name': 'ramesh',
'address': 'vizag',
'mail':'[email protected]',
'age': 45
}
jsondata=json.dumps(data)
r=requests.put(url=URL,data=jsondata)
data=r.json()
print(data)
#update_record()
def delete_data():
data={'id':2}
jsondata=json.dumps(data)
r=requests.delete(url=URL,data=jsondata)
data=r.json()
print(data)
delete_data()
MOHAN S.REDDY
DRF Validations:
Object level validation: This can be used to perform validation on all fields or
multiple fields.
Validators: This can be used to create a validation function with logic that can be
reuse in the application.
Ex:
Serializers.py:
from rest_framework import serializers
from myapp.models import Employee
MOHAN S.REDDY
#validators
def starts_with_s(value):
if value[0].lower()!='s':
raise serializers.ValidationError('Name
should starts with letter s')
class EmployeeSerialzer(serializers.Serializer):
name=serializers.CharField(max_length=20,validators
=[starts_with_s])
address=serializers.CharField(max_length=20)
mail=serializers.CharField(max_length=20)
age=serializers.IntegerField()
instance.name=validated_data.get('name',instance.na
me)
instance.address =
validated_data.get('address', instance.address)
instance.mail = validated_data.get('mail',
instance.mail)
instance.age = validated_data.get('age',
instance.age)
instance.save()
return instance
if value>100:
raise serializers.ValidationError("Age
should not exceed 100")
return value
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:
class Meta:
model=Student
fields=['id','name','address','mail','age']
MOHAN S.REDDY
#fields='__all__'
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp1',
'rest_framework',
]
models.py :
admin.py:
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
MOHAN S.REDDY
serializers.py:
class
StudentSerializer(serializers.ModelSerializer):
# validators
def starts_with_s(value):
if value[0].lower() != 's':
raise serializers.ValidationError('Name
should starts with letter s')
#address=serializers.CharField(read_only=True)
name=serializers.CharField(validators=[starts_with_
s])
class Meta:
model=Student
#fields=['name','address','mail','age']
fields='__all__'
#read_only_fields=['address','age']
MOHAN S.REDDY
views.py:
return HttpResponse(jsondata,
content_type='application/json')
into database'}
jsondata =
JSONRenderer().render(result)
return HttpResponse(jsondata,
content_type='application/json')
jsondata =
JSONRenderer().render(serializer.errors)
return HttpResponse(jsondata,
content_type='application/json')
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('student/',views.studentdata.as_view()),
MOHAN S.REDDY
Create a new python file with the name api.py inside the application.
api.py:
import requests
import json
URL="http://127.0.0.1:8000/student/"
def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
r=requests.get(url=URL,data=jsondata)
data=r.json()
print(data)
#get_record(1)
#get_record()
def post_record():
data = {
'name': 'sairam',
'address': 'hyd',
'mail': '[email protected]',
'age': 26
}
jsondata=json.dumps(data)
r=requests.post(url=URL,data=jsondata)
data=r.json()
print(data)
post_record()
MOHAN S.REDDY
def update_record():
data = {
'id':1,
'name': 'durga',
'address': 'hyd',
'mail':'[email protected]',
'age': 45
}
jsondata=json.dumps(data)
r=requests.put(url=URL,data=jsondata)
data=r.json()
print(data)
#update_record()
def delete_data():
data={'id':4}
jsondata=json.dumps(data)
r=requests.delete(url=URL,data=jsondata)
data=r.json()
print(data)
#delete_data()
DRF api_view:
api_view allow us to define functions that match standard http methods like
GET, POST, PUT ,PATCH etc.
The main functionality of api_view decorator is which takes a list of HTTP
methods that your view should respond.
MOHAN S.REDDY
resquest.data :
request. data returns the parsed content of the request body. This is
similar to the standard request. It includes all parsed content.
Response:
Response objects are initialized with data, which should consist of native
python primitives.
Headers:
HTTP Headers are an important part of the API request and response as they
represent the meta-data associated with the API request and response.
Headers carry information for: Request and Response Body
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp2',
]
Models.py:
class Trainer(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()
admin.py:
@admin.register(Trainer)
class TrainerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
serializer.py:
from rest_framework import serializers
from myapp2.models import Trainer
MOHAN S.REDDY
class
TrainerSerializer(serializers.ModelSerializer):
class Meta:
model=Trainer
fields=['id','name','address','mail','age']
views.py:
urlpatterns = [
path('admin/', admin.site.urls),
MOHAN S.REDDY
path('trainer/',views.trainer_api),
]
Create a new python file with the name test.py inside the application.
test.py:
import requests
import json
URL=" http://127.0.0.1:8000/trainer/"
def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
headers={'content-Type':'application/json'}
r=requests.get(url=URL,headers=headers,data=jsondat
a)
data=r.json()
print(data)
#get_record(1)
get_record()
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
MOHAN S.REDDY
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp2',
]
Models.py:
from django.db import models
admin.py:
from django.contrib import admin
from myapp2.models import Trainer
# Register your models here.
@admin.register(Trainer)
class TrainerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
serializer.py:
class
TrainerSerializer(serializers.ModelSerializer):
class Meta:
model=Trainer
fields=['id','name','address','mail','age']
views.py:
serializer=TrainerSerializer(tr,many=True)
return Response(serializer.data)
if request.method=='POST':
serializer=TrainerSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
inserted"})
return Response(serializer.errors)
if request.method=='PUT':
id=request.data.get('id')
tr=Trainer.objects.get(pk=id)
serializer=TrainerSerializer(tr,data=request.data,p
artial=True)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
updated"})
return Response(serializer.errors)
if request.method=='DELETE':
id=request.data.get('id')
tr=Trainer.objects.get(pk=id)
tr.delete()
return Response({"message":"Record
deleted"})
urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('trainer/',views.trainer_api),
]
Create a new python file with the name test.py inside the application.
test.py:
import requests
import json
URL=" http://127.0.0.1:8000/trainer/"
def get_record(id=None):
data={}
if id is not None:
data={'id':id}
jsondata=json.dumps(data)
headers={'content-Type':'application/json'}
r=requests.get(url=URL,headers=headers,data=jsondat
a)
data=r.json()
print(data)
#get_record(1)
#get_record()
def post_record():
data = {
'name': 'sairam',
'address': 'hyd',
'mail': '[email protected]',
'age': 26
}
jsondata=json.dumps(data)
MOHAN S.REDDY
r=requests.post(url=URL,headers=headers,data=jsonda
ta)
data=r.json()
print(data)
#post_record()
def update_record():
data = {
'id':1,
'name': 'mohan',
'address': 'srnagar',
'mail':'[email protected]',
'age': 30
}
jsondata=json.dumps(data)
headers = {'content-Type': 'application/json'}
r=requests.put(url=URL,headers=headers,data=jsondat
a)
data=r.json()
print(data)
#update_record()
def delete_data():
data={'id':4}
jsondata=json.dumps(data)
headers = {'content-Type': 'application/json'}
r=requests.delete(url=URL,headers=headers,data=json
data)
data=r.json()
print(data)
MOHAN S.REDDY
delete_data()
Ex with CRUD APIView using class based view with browser API testing:
Models.py :
admin.py:
serializer.py :
class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']
views.py :
class ManagerAPI(APIView):
def get(self,request,pk=None,format=None):
id=pk
if id is not None:
m=Manager.objects.get(id=id)
serializer=ManagerSerializer(m)
return Response(serializer.data)
m=Manager.objects.all()
serializer=ManagerSerializer(m,many=True)
return Response(serializer.data)
def post(self,request,format=None):
serializer=ManagerSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({'message':'Data
inserted'},status=status.HTTP_201_CREATED)
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)
MOHAN S.REDDY
def put(self,request,pk,format=None):
id=pk
m=Manager.objects.get(pk=id)
serializer=ManagerSerializer(m,data=request.data)
if serializer.is_valid():
serializer.save()
return Response({'message':"Data is
updated"})
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)
def patch(self,request,pk,format=None):
id=pk
m=Manager.objects.get(pk=id)
serializer=ManagerSerializer(m,data=request.data,pa
rtial=True)
if serializer.is_valid():
serializer.save()
return Response({'message':"partiallly
updated"})
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)
def delete(self,request,pk,format=None):
id=pk
m=Manager.objects.get(pk=id)
m.delete()
return Response({'message':"Record is
deleted"})
urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('manager/',views.ManagerAPI.as_view()),
path('manager/<int:pk>',views.ManagerAPI.as_view())
,
]
Note: to test this, go to browser and then type
http://127.0.0.1:8000/manager/
Types of mixin:
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp4',
]
Models.py:
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()
admin.py:
serializer.py:
from rest_framework import serializers
from myapp4.models import Customer
class
CustomerSerializer(serializers.ModelSerializer):
class Meta:
model=Customer
fields=['id','name','address','mail','age']
MOHAN S.REDDY
views.py:
def get(self,request,*args,**kwargs):
return self.list(request,*args,**kwargs)
class
CustomerCreate(GenericAPIView,CreateModelMixin):
queryset = Customer.objects.all()
serializer_class =CustomerSerializer
def post(self,request,*args,**kwargs):
return self.create(request,*args,**kwargs)
class
CustomerRetrieve(GenericAPIView,RetrieveModelMixin)
:
queryset = Customer.objects.all()
serializer_class =CustomerSerializer
def get(self,request,*args,**kwargs):
return
self.retrieve(request,*args,**kwargs)
MOHAN S.REDDY
class
CustomerUpdate(GenericAPIView,UpdateModelMixin):
queryset = Customer.objects.all()
serializer_class =CustomerSerializer
def put(self,request,*args,**kwargs):
return self.update(request,*args,**kwargs)
class
CustomerDelete(GenericAPIView,DestroyModelMixin):
queryset = Customer.objects.all()
serializer_class =CustomerSerializer
def delete(self,request,*args,**kwargs):
return self.destroy(request,*args,**kwargs)
#Retrieve,Update,Delete
class
Retrive_Update_Delete(GenericAPIView,RetrieveModelM
ixin,UpdateModelMixin,DestroyModelMixin):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
def put(self,request,*args,**kwargs):
return self.update(request,*args,**kwargs)
#List ,Create
MOHAN S.REDDY
class List_Create(GenericAPIView,ListModelMixin,
CreateModelMixin):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
#path('customerlist/',views.CustomerList.as_view())
,
#path('customercreate/',views.CustomerCreate.as_vie
w()),
#path('customerretrieve/<int:pk>',
views.CustomerRetrieve.as_view()),
#path('customerupdate/<int:pk>',
views.CustomerUpdate.as_view()),
#path('customerdelete/<int:pk>',
views.CustomerDelete.as_view()),
path('RUD/<int:pk>',views.Retrive_Update_Delete.as_
view()),
MOHAN S.REDDY
path('LC/',views.List_Create.as_view()),
Concrete views do most of the work that we need to do on our own when
using APIView .
They use mixins as their basic building blocks, combine the building blocks
with GenericAPIView , and bind actions to the methods.
The following are the concrete generic views.
1. ListAPIView
2. CreateAPIView
3. RetrieveAPIView
4. UpdateAPIView
5. DestroyAPIView
6. ListCreateAPIView
7. RetrieveUpdateAPIView
8. RetrieveDestroyAPIView
9. RetrieveUpdateDestroyAPIView
MOHAN S.REDDY
MOHAN S.REDDY
queryset
serializer class
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
MOHAN S.REDDY
'rest_framework',
'myapp5',
]
Models.py:
from django.db import models
admin.py:
from django.contrib import admin
from myapp5.models import Customer
# Register your models here.
@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
list_display =
['id','name','address','mail','age']
serializer.py:
class
CustomerSerializer(serializers.ModelSerializer):
class Meta:
model=Customer
fields=['id','name','address','mail','age']
views.py:
CreateAPIView,RetrieveAPIView,UpdateAPIView,Destroy
APIView,
ListCreateAPIView,RetrieveUpdateAPIView,RetrieveDes
troyAPIView,RetrieveUpdateDestroyAPIView
class CustomerCreate(CreateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class CustomerRetrieve(RetrieveAPIView):
MOHAN S.REDDY
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class CustomerUpdate(UpdateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class CustomerDestroy(DestroyAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class CustomerListCreate(ListCreateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class
CustomerRetrieveUpdate(RetrieveUpdateAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class
CustomerRetrieveDestroy(RetrieveDestroyAPIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
class
CustomerRetrieveUpdateDestroy(RetrieveUpdateDestroy
APIView):
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('customerlist/',views.CustomerList.as_view()),
path('customercreate/',views.CustomerCreate.as_view
()),
path('customerretrieve/<int:pk>',views.CustomerRetr
ieve.as_view()),
path('customerupdate/<int:pk>',views.CustomerUpdate
.as_view()),
path('customerdestroy/<int:pk>',
views.CustomerDestroy.as_view()),
path('customerlistcreate/',views.CustomerListCreate
.as_view()),
path('customerretrieveupdate/<int:pk>',views.Custom
erRetrieveUpdate.as_view()),
path('customerretrievedestroy/<int:pk>',
views.CustomerRetrieveDestroy.as_view()),
path('customerretrieveupdatedestroy/<int:pk>',
views.CustomerRetrieveUpdateDestroy.as_view()),
Django REST framework allows you to combine the logic for a set of related
views in a single class, called a ViewSet.
In other frameworks you may also find conceptually similar
implementations named something like 'Resources' or 'Controllers'.
MOHAN S.REDDY
A ViewSet class is simply a type of class-based View, that does not provide
any method handlers such as .get() or .post(), and instead provides actions
such as .list() and .create().
The method handlers for a ViewSet are only bound to the corresponding
actions at the point of finalizing the view, using the .as_view() method.
Typically, rather than explicitly registering the views in a viewset in the
urlconf, you'll register the viewset with a router class, that automatically
determines the urlconf for you.
Routers are used with ViewSets in django rest framework to auto config the
urls.
Routers provides a simple, quick and consistent way of writing ViewSet
logic to a set of URLs.
Router automatically maps the incoming request to proper viewset action
based on the request method type(i.e GET, POST, etc).
ViewSet attributes:
basename :
The base to use for the URL names that are created.
If unset, the basename will be automatically generated based on the queryset
attribute of the viewset.
Note that if the viewset does not include a queryset attribute then you must
set basename when registering the viewset.
action :
detail:
Return Boolean, indicates that the current action is configured for a list or
detail view.
name :
Settings.py:
MOHAN S.REDDY
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp6',
]
Models.py:
admin.py:
serializer.py:
class
CustomerSerializer(serializers.ModelSerializer):
class Meta:
model=Customer
fields=['id','name','address','mail','age']
views.py:
cust=Customer.objects.all()
serializer=CustomerSerializer(cust,many=True)
return Response(serializer.data)
def retrieve(selfself,request,pk=None):
id=pk
if id is not None:
cust=Customer.objects.get(id=id)
serializer=CustomerSerializer(cust)
return Response(serializer.data)
def create(self,request):
serializer=CustomerSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
inserted"},status=status.HTTP_201_CREATED)
return
Response(serializer.errors,status=status.HTTP_400_B
AD_REQUEST)
def update(self,request,pk):
id=pk
cust=Customer.objects.get(pk=id)
serializer =
CustomerSerializer(cust,data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data
updated"})
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
def partial_update(self,request,pk):
id=pk
cust=Customer.objects.get(pk=id)
MOHAN S.REDDY
serializer =
CustomerSerializer(cust,data=request.data,partial=T
rue)
if serializer.is_valid():
serializer.save()
return Response({"message":"Data is
partially updated"})
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)
def destroy(selfself,request,pk):
id=pk
cust=Customer.objects.get(pk=id)
cust.delete()
return Response({"message":"Record
deleted"})
urls.py :
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
]
MOHAN S.REDDY
ReadOnlyModelViewSet:
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp7',
]
Models.py:
class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()
admin.py:
serializer.py:
class
ManagerSerializer(serializers.ModelSerializer):
MOHAN S.REDDY
class Meta:
model=Manager
fields=['id','name','address','mail','age']
views.py:
#ReadOnlyModelViewSet
'''class
ManagerModelViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer'''
urls.py:
urlpatterns = [
MOHAN S.REDDY
path('admin/', admin.site.urls),
path('',include(router.urls)),
Types of Authentication:
1. Basic Authentication
2. Token Authentication
3. Session Authentication
4. Remote User Authentication
5. Custom Authentication
Permissions:
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:
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp7',
]
Models.py:
class Manager(models.Model):
name=models.CharField(max_length=20)
address=models.CharField(max_length=20)
mail = models.CharField(max_length=20)
age = models.IntegerField()
admin.py:
serializer.py:
class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
MOHAN S.REDDY
model=Manager
fields=['id','name','address','mail','age']
views.py:
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
settings.py:
REST_FRAMEWORK={
'DEFAULT_AUTHENTICATION_CLASSES':['rest_framework.a
uthentication.BasicAuthentication'],
'DEFAULT_PERMISSION_CLASSES':['rest_framework.permi
ssions.IsAuthenticated']
}
Permission classes:
AllowAny :
IsAuthenticated:
MOHAN S.REDDY
IsAdminUser :
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 :
DjangoObjectPermissions :
CustomPermissions:
MOHAN S.REDDY
The methods should return True if the request should be granted access, and
False otherwise.
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp7',
]
Models.py:
serializer.py:
class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']
views.py:
permission_classes = [CustomPermission]
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
path('authentication/',include('rest_framework.urls
',namespace='rest_framework'))
custompermissions.py:
class CustomPermission(BasePermission):
def has_permission(self, request, view):
if request.method=='GET':
return True
return False
INSTALLED_APPS = [
...
'rest_framework.authtoken'
]
MOHAN S.REDDY
Note: Make sure to run manage.py migrate after changing your settings. The
rest_framework.authtoken app provides Django database migrations.
If successfully authenticated, TokenAuthentication provides the following
credentials.
request.user will be a Django User instance.
request.auth will be a rest_framework.authtoken.models.Token instance.
Unauthenticated responses that are denied permission will result in an HTTP
401 Unauthorized response .
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp8',
'rest_framework.authtoken',
Models.py:
MOHAN S.REDDY
serializer.py:
class
MOHAN S.REDDY
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']
views.py:
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
MOHAN S.REDDY
path('authentication/',include('rest_framework.urls
',namespace='rest_framework'))
Go to admin panel, click on tokens, click on Add token, select user for
creating a token and then click on save.
Note: if user has token then it will return that, if user don’t have any token then it
will create a token.
httpie :
urls.py :
MOHAN S.REDDY
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
path('authentication/',include('rest_framework.urls
',namespace='rest_framework')),
path('gettoken/',obtain_auth_token)
]
models.py :
@receiver(post_save,sender=settings.AUTH_USER_MODEL
)
def
create_auth_token(sender,instance=None,created=Fals
e,**kwargs):
if created:
Token.objects.create(user=instance)
Note: in this case as soon as we create a user through signal automatically token
will be create.
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp8',
'rest_framework.authtoken',
MOHAN S.REDDY
Models.py:
@receiver(post_save,sender=settings.AUTH_USER_MODEL
)
def
create_auth_token(sender,instance=None,created=Fals
e,**kwargs):
if created:
Token.objects.create(user=instance)
admin.py:
serializer.py:
class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']
views.py:
class ManagerModelViewSet(viewsets.ModelViewSet):
queryset = Manager.objects.all()
serializer_class = ManagerSerializer
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
path('authentication/',include('rest_framework.urls
',namespace='rest_framework')),
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'myapp8',
Models.py:
from django.db import models
admin.py:
list_display =
['id','name','address','mail','age']
serializer.py:
class
ManagerSerializer(serializers.ModelSerializer):
class Meta:
model=Manager
fields=['id','name','address','mail','age']
class CustomAuthentication(BaseAuthentication):
def authenticate(self, request):
username=request.GET.get('username')
if username is None:
return None
try:
user=User.objects.get(username=username)
except User.DoesNotExist:
raise AuthenticationFailed("User does
not exist")
return (user,None)
views.py:
from myapp8.models import Manager
from myapp8.serializers import ManagerSerializer
from rest_framework import viewsets
from rest_framework.permissions import
IsAuthenticated
from myapp8.authentication import
CustomAuthentication
urls.py:
MOHAN S.REDDY
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
path('authentication/',include('rest_framework.urls
',namespace='rest_framework')),
Click on the ManagerViewset link and try the below link with providing
username
http://127.0.0.1:8000/ManagerViewset/?username=mohan
Filtering in DRF:
MOHAN S.REDDY
Settings.py :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
]
models.py :
admin.py :
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display =
['id','name','sid','saddress','trainedby']
serializer.py:
class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
fields=['id','name','sid','saddress','trainedby']
views.py :
MOHAN S.REDDY
class StudentList(ListAPIView):
queryset = Student.objects.all()
#queryset =
Student.objects.filter(trainedby="user1")
serializer_class = StudentSerializer
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('studentapi/',views.StudentList.as_view()),
]
You might want to filter the queryset to ensure that only results relevant to
the currently authenticated user making the request are returned.
You can do so by filtering based on the value of request.user
Views.py:
class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
def get_queryset(self):
user=self.request.user
return
Student.objects.filter(trainedby=user)
Generic Filtering:
As well as being able to override the default queryset, REST framework also
includes support for generic filtering backends that allow you to easily
construct complex searches and filters.
Generic filters can also present themselves as HTML controls in the
browsable API and admin API.
DjangoFilterBackend:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS':
['django_filters.rest_framework.DjangoFilterBackend']
}
MOHAN S.REDDY
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'django_filters',
]
REST_FRAMEWORK={
'DEFAULT_FILTER_BACKENDS':['django_filters.rest_fra
mework.DjangoFilterBackend']
}
Views.py:
class StudentList(ListAPIView):
queryset = Student.objects.all()
MOHAN S.REDDY
serializer_class = StudentSerializer
filterset_fields=['saddress']
Now you can remove default filter backends from settings.py file and
try below code .
Views.py:
class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields=['saddress','trainedby']
Search Filter:
MOHAN S.REDDY
Settings.py :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'django_filters',
models.py :
admin.py :
MOHAN S.REDDY
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display =
['id','name','sid','saddress','trainedby']
serializer.py:
class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
fields=['id','name','sid','saddress','trainedby']
views.py :
MOHAN S.REDDY
class StudentList(ListAPIView):
queryset = Student.objects.all()
serializer_class = StudentSerializer
filter_backends = [SearchFilter]
search_fields=['saddress']
#search_fields = ['saddress','name']
#search_fields=['^name'] #startswith
#search_fields = ['=name'] #exact match
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('studentapi/',views.StudentList.as_view()),
]
REST_FRAMEWORK={
#'SEARCH_PARAM':'search' #default
'SEARCH_PARAM':'s'
}
Now go to browser: http://127.0.0.1:8000/admin/studentapi/?s=hyderabad
Ordering Filter:
Views.py:
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
Settings.py:
REST_FRAMEWORK={
'DEFAULT_PAGINATION_CLASS':'rest_framework.paginati
on.PageNumberPagination',
'PAGE_SIZE':3
}
You can also set the pagination class on an individual view by using the
pagination_class attribute.
Settings.py :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
MOHAN S.REDDY
'myapp.apps.MyappConfig',
'rest_framework',
'paginationapp',
]
models.py :
admin.py :
serializer.py:
MOHAN S.REDDY
class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
fields=['id','name','address','age']
views.py :
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('studentapi/',views.StudentList.as_view()),
]
MOHAN S.REDDY
Pagination.py:
class MyPagination(PageNumberPagination):
page_size = 3
page_query_param = 'p'
page_size_query_param = 'records'
max_page_size = 5
views.py :
http://127.0.0.1:8000/studentapi/?page=2
http://127.0.0.1:8000/studentapi/?p=2
This pagination style mirrors the syntax used when looking up multiple
database records. The client includes both a "limit" and an "offset" query
parameter.
The limit indicates the maximum number of items to return, and is
equivalent to the page_size in other styles. The offset indicates the starting
position of the query in relation to the complete set of unpaginated items.
To set this globally write the following code in settings.py
REST_FRAMEWORK={
'DEFAULT_PAGINATION_CLASS':'rest_framework.pagination.LimitOffs
etPagination'
}
Settings.py :
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'paginationapp',
]
models.py :
MOHAN S.REDDY
admin.py :
serializer.py:
class
StudentSerializer(serializers.ModelSerializer):
class Meta:
MOHAN S.REDDY
model=Student
fields=['id','name','address','age']
views.py :
urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('studentapi/',views.StudentList.as_view()),
]
Pagination.py:
class MyPagination(LimitOffsetPagination):
default_limit = 5
limit_query_param = 'pagelimit'
offset_query_param = 'pageoffset'
max_limit = 4
views.py :
This pagination style only presents forward and reverse controls, and does
not allow the client to navigate to arbitrary positions.
Cursor based pagination requires that there is a unique, unchanging ordering
of items in the result set.
MOHAN S.REDDY
Pagination.py:
class MyPagination(CursorPagination):
page_size = 3
ordering = 'name'
cursor_query_param = 'c'
Models.py:
class Student(models.Model):
name=models.CharField(max_length=20)
sid=models.IntegerField()
saddress=models.CharField(max_length=20)
admin.py:
@admin.register(Student)
class StudentAdmin(admin.ModelAdmin):
list_display = ['id','name','sid','saddress']
serializers.py:
class
StudentSerializer(serializers.HyperlinkedModelSeria
lizer):
class Meta:
model=Student
fields=['id','url','name','sid','saddress']
views.py:
queryset = Student.objects.all()
serializer_class = StudentSerializer
urls.py:
router=DefaultRouter()
router.register('studentapi',views.StudentModelView
set,basename='student')
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
]
Throttling in DRF:
Ex:
settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp.apps.MyappConfig',
'rest_framework',
'throttleapp',
]
models.py:
admin.py :
@admin.register(Student)
MOHAN S.REDDY
class StudentAdmin(admin.ModelAdmin):
list_display = ['id','name','sid','saddress']
serializers.py:
class
StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
fields=['id','url','name','sid','saddress']
views.py:
urls.py:
router=DefaultRouter()
router.register('studentapi',views.StudentModelView
Set,basename='student')
urlpatterns = [
path('admin/', admin.site.urls),
path('',include(router.urls)),
path('auth/',include('rest_framework.urls',namespac
e='rest_framework'))
]
settings.py:
REST_FRAMEWORK={
'DEFAULT_THROTTLE_RATES':{
'anon':'3/day',
'user':'4/hour',
}
}
Note: non authenticated user can make 3 requests per day and authenticated user
can make 4 requests per hour.
throttling.py :
MOHAN S.REDDY
class MohanRateThrottle(UserRateThrottle):
scope='Mohan'
views.py :
settings.py :
REST_FRAMEWORK={
'DEFAULT_THROTTLE_RATES':{
'anon':'3/day',
'user':'4/hour',
'Mohan':'2/minute'
MOHAN S.REDDY
}
}
REST_FRAMEWORK={
'DEFAULT_THROTTLE_CLASSES':[
'rest_framework.throttling.AnonRateThrottle',
'rest_framework.throttling.UserRateThrottle'
],
'DEFAULT_THROTTLE_RATES':{
'anon':'100/day',
'user':'1000/day'