Rest API Interview Faq's
Rest API Interview Faq's
on
RESTful Web Services
1 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q1) Explain what is REST and RESTFUL?
☻ REST was first introduced by Roy Fielding in 2000.
☻ REST stands for REpresentational State Transfer. It means that each unique URL is
a represention of some object. it focuses on how state of resource should be
transported over HTTP protocol to different clients written in different languages.
RESTFul API:
The API which is developed by using REST Architecture is nothing but RESTFul API. i.e
interface between the user and application where API implements REST Architecture. In
RESTFUL web service HTTP methods like GET, POST, PUT, PATCH and DELETE can be used
to perform CRUD operations
Note: REST is basically an architecture where as RESTFul API is an API that implements
REST.
Q2) Explain the architectural style for creating any web API based on REST?
The architectural style for creating web api are
1) We can use HTTP for client server communication
2) We can use XML/JSON to send and receive messages. i.e XML/JSON acts as
formatting language.
3) Each resource/service can be accessed by a unique URL. This URL acts as the
address for the resource/service.
4) Stateless communication
2 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q5) What is a "Resource" in REST?
REST architecture treats any content as a resource, which can be either database
record, text files, HTML pages, images, videos or dynamic business information.
Consumer application can send
☻ GET request to access a resource,
☻ POST request to create a resource,
☻ PUT/PATCH request to update a resource,
☻ DELETE request to delete a resource.
3 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q11) Explain the difference between PUT and PATCH?
We can use PUT for full updation where as PATCH for partial updation of resources.
Diagram
1) Request Line:
It contains 3 parts
1) Request Method like GET,POST etc
2) Resource Path (like /api/2/)
3) Protocol version used by browser(HTTP/1.1)
2) Request Headers:
It contains configuration information of the browser(like media types accepted by
browser,encoding types supported by browser) and extra information about request
body
3) Request Body:
It contains original information provided by the client.
Diagram
1) Status Line:
It contains 3 parts
1) HTTP protocol version used by server (HTTP/1.1)
2) Status Code (200)
4 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3) Description of the status code (OK)
2) Response Headers:
It contains extra information about response body like content type, content length
etc
3) Response Body:
It contains original response (like JSON) which intended for client.
Q16) What is the upper limit for a payload to pass in the POST method?
In GET request, the data will be appended to the service URL. There is a limit on length of
URL. Hence limit is applicable for payload of GET request.
In POST request, the payload (data) will be encapsulated in request body, which is not
having any size limit. Hence there is no limit for payload of POST request.
Q17) Explain the term 'Statelessness' with respect to RESTful WEB service?
Statelessness means complete isolation. Server won't maintain any information of the
client. Every request to the server is treated as an independent new request. With every
request client is responsible to send authentication information also like Tokens etc.
Advantages:
1) Every request to the server is considered as independent request. i.e there are no
dependencies to previous requests.
2) Any previous communication with the client and server is not maintained and hence
the total process is simplified.
3) Every request contains complete information.
4) Without effecting client applications, we can restart server.
Disadvantages:
1) With every request, compulsory client should send extra information like
authentication tokens etc. It is a burden to the client application.
2) It causes network traffic problems and require more bandwidth.
5 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
The main advantages of caching are:
Only the client is able to cache the response and that too for a limited period of time.
Mentioned below are the header of the resources and their brief description so that they
can be identified for the caching process:
Q20) What is status code and what are various possible HTTP status codes?
HTTP status code represent the status of the response like success or fail etc. The
following are various possible HTTP status codes
1XX Informational
2XX Successful
3XX Redirection
4XX Client Error
5XX Server Error
Q21) List out some common status codes experienced in your previous
project?
Eg 1:
Code 200: This indicates success.
If we send GET request and the requested resource is available then we will get response
with 200 status code.
Eg 2:
Code 201: This indicates resource has been successfully created.
If we send POST request and if the resource created successfully then we will get 201
status code response
Eg 3:
Code 204: This indicates that there is no content in the response body.
6 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
If we send DELETE request and if the resource deleted successfully then we will get 204
status code response.
Eg 4:
Code 404: This indicates that there is no method available.
If we send GET request and if the requested resource is not available then we will get 404
status code response.
Eg 5:
code 400
It means, BAD REQUEST, states that invalid input is provided e.g. validation error, missing
data.
Eg 6:
401 Unauthorized
If authentication information is not provided when we will get 401 Unauthorized
response.
Eg 7:
403 Forbidden
If csrf verification fails then we will get 403 status code response.
Eg 8: 500
It means, INTERNAL SERVER ERROR, states that server has thrown some exception while
processing our request.
Q22) What are the best practices that are to be followed while designing
RESTful web services?
The following are various best practices while desiging RESTful web services
1) Every input on the server should be validated.
2) Input should be well formed.
3) Never pass any sensitive data through URL.
4) For any session, the user should be authenticated.
5) Only HTTP error messages should be used for indicating any fault.
6) Use message format that is easily understood and is required by the client.
7) end point(URL) should be descriptive and easily understandable.
7 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Django REST Framework
(DRF)
Interview
Questions
8 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Q1. Explain the following?
1. API
2. Web API
3. REST
4. RESTful Web API
Q8. From the python program, how we can send HTTP Request?
By using requests module, we can send HTTP request from python script
eg:
import requests
BASE_URL='http://127.0.0.1:8000/'
ENDPOINT='api'
r=requests.get(BASE_URL+ENDPOINT)
data=r.json()
print('Employee Number:',data['eno'])
print('Employee Name:',data['ename'])
print('Employee Salary:',data['esal'])
9 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
print('Employee Address:',data['eaddr'])
In multiple inheritance, we can create object for parent class and parent class can extend
other classes. But in Mixins, for the parent class we cannot create object and it should be
direct child class of object.i.e parent class cannot extend any other classes.
In Multiple inheritance, parent class can contain instance variables.But in Mixins, parent
class cannot contain instance variable but can contain class level static variables.
Hence the main purpose of parent class in Mixins is to provide functions to the child
classes.
Note:
1. Mixins are reusable classes in django.
2. Mixins are available only in languages which provide support for multiple inheritance
like Python,Ruby,Scala etc
Mixins are not applicable for Java and C#,because these languages won't support multiple
inheritance.
10 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
mixins.py:
----------
from django.http import JsonResponse
class JsonResponseMixin(object):
def render_to_json_response(self,context,**kwargs):
return JsonResponse(context,**kwargs)
CBV:
----
from testapp.mixins import JsonResponseMixin
class JsonCBV2(JsonResponseMixin,View):
def get(self,request,*args,**kwargs):
employee_data={'eno':100,'ename':'Sunny Leone','esal':1000,'eaddr':'Hyderabad'}
return self.render_to_json_response(employee_data)
Q13. In Django REST Framework, what are various predefined Mixin classes available?
1. ListModelMixin
2. CreateModelMixin
3. RetrieveModelMixin
4. UpdateModelMixin
5. DestroyModelMixin
11 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
----------------------------------
models.py:
---------
from django.db import models
class Employee(models.Model):
eno=models.IntegerField()
ename=models.CharField(max_length=64)
esal=models.FloatField()
eaddr=models.CharField(max_length=64)
serializers.py:
---------------
from rest_framework import serializers
class EmployeeSerializer(serializers.Serializer):
eno=serializers.IntegerField()
ename=serializers.CharField(max_length=64)
esal=serializers.FloatField()
eaddr=serializers.CharField(max_length=64)
12 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
[OrderedDict([('eno', 100), ('ename', 'Durga'), ('esal', 1000.0), ('eaddr', 'Hyderabad')]),
OrderedDict([('eno', 200), ('ename', 'Bunny'), ('esal', 2000.0), ('eaddr', 'Mumbai')])]
>>> json_data=JSONRenderer().render(eserializer.data)
>>> json_data
b'[{"eno":100,"ename":"Durga","esal":1000.0,"eaddr":"Hyderabad"},{"eno":200,"ename
":"Bunny","esal":2000.0,"ead
dr":"Mumbai"}]'
Q16. How to use dumpdata option, to display database data to the console?
We can dump our database data either to the console or to the file by using dumpdata
option. This option provides support for json and xml formats. The default format is json.
We can write this data to files also.
commands:
---------
py manage.py dumpdata testapp.Employee
print data to the console in json format without identation
py manage.py dumpdata testapp.Employee --indent 4
print data to the console in json format with identation
py manage.py dumpdata testapp.Employee >emp.json --indent 4
write data to emp.json file instead of displaying to the console
py manage.py dumpdata testapp.Employee --format json >emp.json --indent 4
we are specifying format as json explicitly
py manage.py dumpdata testapp.Employee --format xml --indent 4
print data to the console in xml format with identation
py manage.py dumpdata testapp.Employee --format xml > emp.xml --indent 4
write data to emp.xml file instead of displaying to the console
Just for our testing purposes we can disable CSRF verification, but not recommended in
production environment.
13 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
----------------------------------------
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def my_view(request):
body
code:
@method_decorator(csrf_exempt,name='dispatch')
class EmployeeListCBV(SerializeMixin,View):
pass
'django.middleware.csrf.CsrfViewMiddleware'
Q18. Without using any 3rd party REST Frameworks(like DRF), implement the following
HTTP Methods functionality?
1. GET/List/Retrieve
2. POST/Create
3. PUT/Update
4. DELETE/destroy
Answer:
models.py:
----------
from django.db import models
14 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
eno=models.IntegerField()
ename=models.CharField(max_length=64)
esal=models.FloatField()
eaddr=models.CharField(max_length=64)
admin.py:
---------
from django.contrib import admin
from testapp.models import Employee
# Register your models here.
class EmployeeAdmin(admin.ModelAdmin):
list_display=['id','eno','ename','esal','eaddr']
admin.site.register(Employee,EmployeeAdmin)
forms.py:
---------
from django import forms
from testapp.models import Employee
class EmployeeForm(forms.ModelForm):
#validations
def clean_esal(self):
inputsal=self.cleaned_data['esal']
if inputsal < 5000:
raise forms.ValidationError('The minimum salary should be 5000')
return inputsal
class Meta:
model=Employee
fields='__all__'
mixins.py:
---------
from django.core.serializers import serialize
import json
class SerializeMixin(object):
def serialize(self,qs):
json_data=serialize('json',qs)
pdict=json.loads(json_data)
final_list=[]
for obj in pdict:
final_list.append(obj['fields'])
json_data=json.dumps(final_list)
return json_data
15 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
from django.http import HttpResponse
class HttpResponseMixin(object):
def render_to_http_response(self,data,status=200):
return HttpResponse(data,content_type='application/json',status=status)
utils.py:
---------
import json
def is_json(data):
try:
real_data=json.loads(data)
valid=True
except ValueError:
valid=False
return valid
urls.py:
--------
from django.conf.urls import url
from django.contrib import admin
from testapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/$', views.EmployeeCRUDCBV.as_view()),
# url(r'^api/$', views.EmployeeListCBV.as_view()),
]
views.py:
---------
from django.shortcuts import render
from django.views.generic import View
from testapp.models import Employee
import json
from django.http import HttpResponse
from django.core.serializers import serialize
from testapp.mixins import SerializeMixin,HttpResponseMixin
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from testapp.utils import is_json
from testapp.forms import EmployeeForm
@method_decorator(csrf_exempt,name='dispatch')
class EmployeeCRUDCBV(HttpResponseMixin,SerializeMixin,View):
def get_object_by_id(self,id):
try:
emp=Employee.objects.get(id=id)
16 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
except Employee.DoesNotExist:
emp=None
return emp
def get(self,request,*args,**kwargs):
data=request.body
if not is_json(data):
return self.render_to_http_response(json.dumps({'msg':'plz send valid json data
only'}),status=400)
data=json.loads(request.body)
id=data.get('id',None)
if id is not None:
obj=self.get_object_by_id(id)
if obj is None:
return self.render_to_http_response(json.dumps({'msg':'No Matched Record
Found with Specified Id'}),status=404)
json_data=self.serialize([obj,])
return self.render_to_http_response(json_data)
qs=Employee.objects.all()
json_data=self.serialize(qs)
return self.render_to_http_response(json_data)
def post(self,request,*args,**kwargs):
data=request.body
if not is_json(data):
return self.render_to_http_response(json.dumps({'msg':'plz send valid json data
only'}),status=400)
empdata=json.loads(request.body)
form=EmployeeForm(empdata)
if form.is_valid():
obj = form.save(commit=True)
return self.render_to_http_response(json.dumps({'msg':'resource created
successfully'}))
if form.errors:
json_data=json.dumps(form.errors)
return self.render_to_http_response(json_data,status=400)
def put(self,request,*args,**kwargs):
data=request.body
if not is_json(data):
return self.render_to_http_response(json.dumps({'msg':'plz send valid json data
only'}),status=400)
data=json.loads(request.body)
id=data.get('id',None)
if id is None:
17 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
return self.render_to_http_response(json.dumps({'msg':'To perform updation id is
mandatory,you should provide'}),status=400)
obj=self.get_object_by_id(id)
if obj is None:
json_data=json.dumps({'msg':'No matched record found, Not possible to perform
updataion'})
return self.render_to_http_response(json_data,status=404)
new_data=data
old_data={
'eno':obj.eno,
'ename':obj.ename,
'esal':obj.esal,
'eaddr':obj.eaddr,
}
# for k,v in new_data.items():
# old_data[k]=v
old_data.update(new_data)
form=EmployeeForm(old_data,instance=obj)
if form.is_valid():
form.save(commit=True)
json_data=json.dumps({'msg':'Updated successfully'})
return self.render_to_http_response(json_data,status=201)
if form.errors:
json_data=json.dumps(form.errors)
return self.render_to_http_response(json_data,status=400)
def delete(self,request,*args,**kwargs):
data=request.body
if not is_json(data):
return self.render_to_http_response(json.dumps({'msg':'plz send valid json data
only'}),status=400)
data=json.loads(request.body)
id=data.get('id',None)
if id is None:
return self.render_to_http_response(json.dumps({'msg':'To perform delete, id is
mandatory,you should provide'}),status=400)
obj=self.get_object_by_id(id)
if obj is None:
json_data=json.dumps({'msg':'No matched record found, Not possible to perform
delete operation'})
return self.render_to_http_response(json_data,status=404)
status,deleted_item=obj.delete()
if status==1:
json_data=json.dumps({'msg':'Resource Deleted successfully'})
return self.render_to_http_response(json_data,status=201)
18 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
json_data=json.dumps({'msg':'unable to delete ...plz try again'})
return self.render_to_http_response(json_data,status=500)
test.py:
--------
import requests
import json
BASE_URL='http://127.0.0.1:8000/'
ENDPOINT='api/'
def get_resources(id=None):
data={}
if id is not None:
data={
'id':id
}
resp=requests.get(BASE_URL+ENDPOINT,data=json.dumps(data))
print(resp.status_code)
print(resp.json())
def create_resource():
new_emp={
'eno':2000,
'ename':'Katrina',
'esal':20000,
'eaddr':'Mumbai',
}
r=requests.post(BASE_URL+ENDPOINT,data=json.dumps(new_emp))
print(r.status_code)
# print(r.text)
print(r.json())
create_resource()
def update_resource(id):
new_data={
'id':id,
'eno':7777,
'ename':'Kareena',
'eaddr':'Lanka',
'esal':15000
}
r=requests.put(BASE_URL+ENDPOINT,data=json.dumps(new_data))
print(r.status_code)
# print(r.text)
print(r.json())
def delete_resource(id):
data={
'id':id,
19 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
}
r=requests.delete(BASE_URL+ENDPOINT,data=json.dumps(data))
print(r.status_code)
# print(r.text)
print(r.json())
Q19. What are various frameworks are available to develop WEB APIs for Django
Application?
1. Tastify
2. Django REST Framework(DRF)
etc
1. Serialization
2. Deserialization
3. Validation
20 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
eg: To check esal should be minimum 5000
class EmployeeSerializer(serializers.Serializer):
....
def validate_esal(self,value):
if value<5000:
raise serializers.ValidationError('Employee Salaray Should be Minimum 5000')
return value
def validate(self,data):
ename=data.get('ename')
esal=data.get('esal')
if ename.lower()=='sunny':
if esal<60000:
raise serializers.ValidationError('Sunny Salary should be minimum 60K')
return data
use cases:
1. first entered pwd and re-entered pwd must be same.
2. First entered account number and re-entered account number must be same
class EmployeeSerializer(serializers.Serializer):
...
esal=serializers.FloatField(validators=[multiples_of_1000,])
..
21 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1. validations by using validator
2. validations at field level
3. validations at object level
1. Simple/Normal Serializer
2. ModelSerializer
3. Nested Serializer
etc
Q24. What are various advantages of using ModelSerializer when compared with Normal
Serializer?
If our serializable objects are Django model objects, then it is highly recommended to go
for ModelSerializer.
ModelSerializer class is exactly same as regular serializer classe except the following
differences
1. The fields will be considered automatically based on the model and we are not required
to specify explicitly.
Note: ModelSerializer won't provide any extra functionality and it is just for typing
shortcut.
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model=Employee
fields='__all__'
Here we are not required to specify fields and these will be considered automatically
based on Model class. We are not required to implement create() and update() methods,
because ModelSerializer class will provide these methods.
3 ways
22 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
2. To include only some fields
fields=('eno','ename','eaddr')
This approach is helpful if we want to include very less number of fields.
DRF provides 2 classes to define business logic for our API Views.
1. APIView
2. ViewSet
views.py:
--------
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from testapp.serializers import NameSerializer
# Create your views here.
class TestApiView(APIView):
def get(self,request,format=None):
colors=['RED','BLUE','GREEN','YELLOW','INDIGO']
return Response({'msg':'Welcome to Colorful Year','colors':colors})
def post(self,request):
serializer=NameSerializer(data=request.data)
if serializer.is_valid():
name=serializer.data.get('name')
msg='Hello {} Wish You Happy New Year !!!'.format(name)
return Response({'msg':msg})
return Response(serializer.errors,status=400)
def put(self,request,pk=None):
return Response({'msg':'Response from put method'})
def patch(self,request,pk=None):
return Response({'msg':'Response from patch method'})
def delete(self,request,pk=None):
return Response({'msg':'Response from delete method'})
23 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
serializers.py:
---------------
from rest_framework import serializers
class NameSerializer(serializers.Serializer):
name = serializers.CharField(max_length=7)
urls.py:
--------
from django.conf.urls import url,include
from django.contrib import admin
from testapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', views.TestApiView.as_view()),
]
Q28. If we are using APIView class to define CBV, then which methods we have to provide
implementation?
get(),post(),put(),patch(),delete()
Complete Application:
---------------------
views.py:
---------
from rest_framework.response import Response
from testapp.serializers import NameSerializer
from rest_framework import viewsets
class TestViewSet(viewsets.ViewSet):
def list(self,request):
colors=['RED','GREEN','YELLOW','ORANGE']
return Response({'msg':'Wish YOu Colorful Life in 2019','colors':colors})
def create(self,request):
serializer=NameSerializer(data=request.data)
if serializer.is_valid():
name=serializer.data.get('name')
msg='Hello {} Your Life will be settled in 2019'.format(name)
return Response({'msg':msg})
return Response(serializer.errors,status=400)
def retrieve(self,request,pk=None):
return Response({'msg':'Response from retrieve method'})
def update(self,request,pk=None):
24 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
return Response({'msg':'Response from update method'})
def partial_update(self,request,pk=None):
return Response({'msg':'Response from partial_update method'})
def destroy(self,request,pk=None):
return Response({'msg':'Response from destroy method'})
serializers.py:
--------------
from rest_framework import serializers
class NameSerializer(serializers.Serializer):
name = serializers.CharField(max_length=7)
urls.py:
---------
from django.conf.urls import url,include
from django.contrib import admin
from testapp import views
from rest_framework import routers
router=routers.DefaultRouter()
router.register('test-viewset',views.TestViewSet,base_name='test-viewset')
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^api/', views.TestApiView.as_view()),
url(r'',include(router.urls))
]
Q30. If we are using ViewSet to develop CBV, then which methods we have to provide
implementation?
list(),create(),retrieve(),update(),partial_update(),destroy()
25 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
Length of the code is less
6. API Development time is more
API Development time is less
7. Developer has complete control over the logic
Developer won't have complete control over the logic.
8. Clear Execution Flow is possible
Clear Execution Flow is not possible
9. Best suitable for complex operations like using multiple data sources simultaneously,
calling other APIs etc
Best suitable for developing simple APIs like developing CRUD interface for database
models.
ListAPIView
CreateAPIView
RetrieveAPIView
UpdateAPIView
DestroyAPIView
ListCreateAPIView
RetrieveUpdateAPIView
RetrieveDestroyAPIView
RetrieveUpdateDestroyAPIView
Q34. How to develop API to perform CRUD operations by using generic APIView classes?
views.py:
---------
class EmployeeListCreateAPIView(generics.ListCreateAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
class EmployeeRetrieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
lookup_field='id'
26 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
urls.py:
--------
url(r'^api/$', views.EmployeeListCreateAPIView.as_view()),
url(r'^api/(?P<id>\d+)/$', views.EmployeeRetrieveUpdateDestroyAPIView.as_view()),
Q35. How to develop API to perform CRUD operations by using Mixin classes?
Demo Application:
------------------
from rest_framework import mixins
class EmployeeListModelMixin(mixins.CreateModelMixin,generics.ListAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
def post(self,request,*args,**kwargs):
return self.create(request,*args,**kwargs)
class
EmployeeDetailAPIViewMixin(mixins.UpdateModelMixin,mixins.DestroyModelMixin,gen
erics.RetrieveAPIView):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
def put(self,request,*args,**kwargs):
return self.update(request,*args,**kwargs)
def patch(self,request,*args,**kwargs):
return self.partial_update(request,*args,**kwargs)
def delete(self,request,*args,**kwargs):
return self.destroy(request,*args,**kwargs)
url(r'^api/$', views.EmployeeListModelMixin.as_view()),
url(r'^api/(?P<pk>\d+)/$', views.EmployeeDetailAPIViewMixin.as_view()),
Q37) What is Authentication and what are various authentication mechanisms we can
apply in DRF?
The process of validating user is called authentication. Most of the times we can perform
authentication by using username and password combination or by using tokens etc
27 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
DRF provides several inbuilt authentication mechanisms
1. Basic Authentication
2. Session Authentication
3. Token Authentication
4. JWT(Json Web Token) Authentication
etc
Note: By using DRF, we can implement our own custom authentication mechanism also
Q38) What is Autherization and what are various predefined authorization mechanisms
available in DRF?
1. AllowAny
2. IsAuthenticated
3. IsAdminUser
4. IsAuthenticatedOrReadOnly
5. DjangoModelPermissions
6. DjangoModelPermissionsOrAnonReadOnly
etc
Q39) How to enable authentication and authorization for django rest api globally?
REST_FRAMEWORK={
'DEFAULT_AUTHENTICATION_CLASSES':('rest_framework.authentication.TokenAuthentica
tion',),
'DEFAULT_PERMISSION_CLASSES':('rest_framework.permissions.IsAuthenticated',)
Q40) How to enable authentication and authorization for django rest api locally for a
particular View class?
our application may contain several view classes. If we want to enable authentication and
authorization for a particular view class then we have to use this local approach.
28 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
...
authentication_classes=[TokenAuthentication,]
permission_classes=[IsAuthenticated,]
1. AllowAny
2. IsAuthenticated
3. IsAdminUser
4. IsAuthenticatedOrReadOnly
5. DjangoModelPermissions
6. DjangoModelPermissionsOrAnonReadOnly
1. AllowAny:
------------
The AllowAny permission class will allow unrestricted access irrespective of whether
request is authenticated or not.
This is default value for permission-class. It is very helpful to allow unrestricted access for
a particular view class if global settings are enabled.
2. IsAuthenticated:
-------------------
The IsAuthenticated permission class will deny permissions to any unauthorized user. ie
only authenticated users are allowed to access endpoint.
This permission is suitable, if we want our API to be accessible by only registered users.
Note:
We can send Token in postman inside Headers Section
Key: Authorization
Value: Token 3639020972202cc1d25114ab4a5f54e6078184a4
3. IsAdminUser:
---------------
If we use IsAdminUser permission class then only AdminUser is allowed to access.i.e the
users where is_staff property is True.
This type of permission is best suitable if we want our API to be accessible by only trusted
administrators.
If the user is not admin and if he is trying to access endpoint then we will get 403 status
code error response saying:
29 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
{
"detail": "You do not have permission to perform this action."
}
Note:
-----
Normal User ---> can not access admin interface
Admin---> can login to admin interface but no permissions to modify anything
Superuser---> can login to admin interface and can modify anything
4. IsAuthenticatedOrReadOnly:
-----------------------------
To perform read operation (safe methods:GET,HEAD,OPTIONS) authentication is not
required. But for the remaining operations(POST,PUT,PATCH,DELETE) authentication must
be required.
If any person is allowed to perform read operation and only registered users are allowed
to perform write operation then we should go for this permission class.
5. DjangoModelPermissions :
---------------------------
This is the most powerful permission class. Authorization will be granted iff user is
authenticated and has the relevant model permissions.
If the user is not authenticated(we are not providing token) then we will get 401
Unauthorized error message saying
{
"detail": "Authentication credentials were not provided."
}
If we are providing Token (authenticated) but not having model permissions then we can
perform only GET operation. But to perform POST,PUT,PATCH,DELETE compulsory model
permissions must be required,otherwise we will get 403 Forbidden error message saying
{
"detail": "You do not have permission to perform this action."
}
30 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
---------------------------------
To perform POST operation the required model permission is 'add'
To perform PUT,PATCH operations the required model permission is 'change'
To pderform DELETE operation the required model permission is 'delete'
We have to provide these model permissions in admin interface under User permissions:
Note:
1. DjangoModelPermissions class is more powerful and we have complete control on
permissions.
***2. For superuser we are not required to give model permissions explicitly and already
avaialble
6. DjangoModelPermissionsOrAnonReadOnly:
----------------------------------------
It is exactly same as DjangoModelPermissions class except that it allows unauthenticated
users to have read-only access to the API.
eg:
from rest_framework.viewsets import ModelViewSet
from testapp.models import Employee
from testapp.serializers import EmployeeSerializer
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import
IsAuthenticated,AllowAny,IsAdminUser,IsAuthenticatedOrReadOnly,DjangoModelPermiss
ions,DjangoModelPermissionsOrAnonReadOnly
class EmployeeCRUDCBV(ModelViewSet):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
authentication_classes=[TokenAuthentication,]
permission_classes=[DjangoModelPermissionsOrAnonReadOnly,]
Based on our programming requirement, we can define our own permission classes also.
We have to create child class for BasePermission class and we have to override
has_permission() method.
eg1: Define our own Permission class which allows only SAFE_METHODS
(GET,HEAD,OPTIONS)
31 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
permissions.py:
--------------
from rest_framework.permissions import BasePermission,SAFE_METHODS
class IsReadOnly(BasePermission):
def has_permission(self,request,view):
if request.method in SAFE_METHODS:
return True
else:
return False
views.py:
---------
from rest_framework.viewsets import ModelViewSet
from testapp.models import Employee
from testapp.serializers import EmployeeSerializer
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import
IsAuthenticated,AllowAny,IsAdminUser,IsAuthenticatedOrReadOnly,DjangoModelPermiss
ions,DjangoModelPermissionsOrAnonReadOnly
from testapp.permissions import IsReadOnly
class EmployeeCRUDCBV(ModelViewSet):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
authentication_classes=[TokenAuthentication,]
permission_classes=[IsReadOnly,]
eg2: Defining our own permission class which allows only GET and PATCH methods.
eg3: Define our own permission class with the following requirement:
32 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
class SunnyPermission(BasePermission):
def has_permission(self,request,view):
username=request.user.username
if username.lower()=='sunny':
return True
elif username != '' and len(username) %2 == 0 and request.method in
SAFE_METHODS:
return True
else:
return False
To over come this problem, we should go for JWT Authentication. The main advantage of
JWT Authentication over TokenAuthentication is database interaction is not required to
identify user. From the token itself,DRF can identify user, which improves performance
and scalability of the application.
Because of this advantage,JWTAuthentication is the most commonly used type of
authentication in real time.
process:
1. We have to write our Custom Authentication class by extending from
BaseAuthentication.
2. We have to override authenticate() method.
33 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
3. Returns a tuple of (user,None) for successful authentication
4. Raise AuthenticationFailed exception for failed authentication.
authentications.py:
------------------
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from django.contrib.auth.models import User
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('No such type of user')
return (user,None)
views.py:
--------
from testapp.authentications import CustomAuthentication
class EmployeeCRUDCBV(ModelViewSet):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
authentication_classes=[CustomAuthentication,]
permission_classes=[IsAuthenticated,]
eg:
34 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
username: durga
secrete key: a7ZXd98
http://127.0.0.1:8000/api/?username=durga&key=a7ZXd98
authentications.py:
-------------------
from rest_framework.authentication import BaseAuthentication
from django.contrib.auth.models import User
from rest_framework.exceptions import AuthenticationFailed
class CustomAuthentication2(BaseAuthentication):
def authenticate(self,request):
username=request.GET.get('username')
key=request.GET.get('key')
if username is None or key is None:
return None
c1=len(key) == 7
c2=key[0]==username[-1].lower()
c3=key[2]=='Z'
c4=key[4]==username[0]
try:
user=User.objects.get(username=username)
except User.DoesNotExist:
raise AuthenticationFailed('Your provided username is invalid,plz provide valid
username to access endpoint')
if c1 and c2 and c3 and c4:
return (user,None)
raise AuthenticationFailed('Your provided key is invalid,plz provide valid key to
access endpoint')
views.py:
---------
from rest_framework.viewsets import ModelViewSet
from testapp.models import Employee
from testapp.serializers import EmployeeSerializer
from rest_framework.permissions import IsAuthenticated
from testapp.authentications import CustomAuthentication2
class EmployeeCRUDCBV(ModelViewSet):
queryset=Employee.objects.all()
serializer_class=EmployeeSerializer
authentication_classes=[CustomAuthentication2,]
permission_classes=[IsAuthenticated,]
35 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
1. PageNumberPagination
2. LimitOffsetPagination
3. CursorPagination
2. If we want the resources based on specified limit and offset then we should go for
LimitOffsetPagination. Here we have choice to specify offset value from where we have to
consider resources. We cannot specify ordering.
Sometimes we can use one serializer inside another serializer to serialize dependent
Model fields, such type of serializers are called Nested Serializers.
eg1: Assume there are two Models named with Author and Book. Book model has
ForiegnKey reference to Author. While listing Author information, the corresponding
Books information also required to provide. Hence inside AuthorSerializer, we required
use BookSerializer. This concept is nothing but Nested Serializers.
syntax:
class AuthorSerializer(serializers.ModelSerializer):
books_by_author=BookSerializer(read_only=True,many=True)
....
eg2: Assume there are two Models named with Musician and Album. Album model has
ForiegnKey reference to Musician. While listing Musician information, the corresponding
Albums information also required to provide. Hence inside MusicianSerializer, we
required use AlbumSerializer. This concept is nothing but Nested Serializers.
syntax:
class MusicianSerializer(serializers.ModelSerializer):
albums_by_musician=AlbumSerializer(read_only=True,many=True)
36 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
....
Q50. Have you ever consumed 3rd party external APIs in your django project?
Yes, to get geographic information based on ip address, we consumed ipstack api.
SOAP based web services are more secured. We can consume by using RPC Method calls.
These web services can provide support for multiple protocols like HTTP,SMTP,FTP etc
Limitations:
-----------
1. SOAP Based web services will always provide data only in XML format. Parsing of this
XML data is very slow,which creates performance problems.
37 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
REST stands for Representational State Transfer. It means that each unique URL is a
represention of some object. We can get contents of this object by using HTTP GET,we can
modify by using PUT/PATCH and we can delete by using DELETE.
We can create by using POST.
Most of the times RESTful web service will provide data in the form of JSON, parsing is not
difficult. Hence this type of web services are faster when compared with SOAP based Web
Services.
Limitations:
1. It is less secured
2. It provide support only for the protocols which can provide URI, mostly HTTP.
38 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in
8. Performance is Low
Perforamnce is High
9. More Secured
Less Secured
39 NARESH IT, 2nd Floor, Durga Bhavani Complex, Satyam Threater Rd, Ameerpet, HYD
Telangana-500016 | Tel:+91 40 2374 6666 | Ph:+91 90009 94007 | www.nareshit.in