- DJANGO REST APIĀ VIDEO
- myproject>python manage.py startapp student
pip install djangorestframework
- add mywebsite/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp',
'student',
'rest_framework',
]
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
]
}
python manage.py makemigrations
python manage.py migrate
#############################
##########
myapp/serializers.py
from rest_framework import serializers
from .models import Student2
class Student2Serializer(serializers.ModelSerializer):
Ā Ā class Meta:
Ā Ā Ā model=Student2
Ā Ā Ā fields=("name","ph","course")
Ā Ā Ā # fields='__all__
myapp/models.py
lass Student2(models.Model):
Ā Ā Ā name=models.CharField(max_length=50)
Ā Ā Ā ph=models.IntegerField()
Ā Ā Ā email_id=models.EmailField(max_length=50)
Ā Ā Ā course=models.CharField(max_length=50)
Ā Ā Ā trainer =Ā models.ForeignKey(Trainer, on_delete=models.CASCADE)
Ā Ā Ā def __str__(self):
Ā Ā Ā Ā s=self.name+" "+str(self.ph)+" "+str(self.email_id)+" "+self.course
Ā Ā Ā Ā return s
Views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Student2
from .serializers import Student2Serializer
# List all students or add new student into DB
class StudentList(APIView):
Ā Ā # # List all students
Ā Ā def get(self,request):
Ā Ā Ā stdnts=Student2.objects.all()
Ā Ā Ā # Convert all objects into serialized data
Ā Ā Ā serializer=Student2Serializer(stdnts,many=True)
Ā Ā Ā # Return serialized data
Ā Ā Ā return Response(serializer.data)
Ā Ā #add new student into DB
Ā Ā def post(self,request):
Ā Ā Ā Ā pass
enquiry/urls.py
Ā Ā re_path('rest/',views.StudentList.as_view() ),
POST/ UPDATE data
{
"stdnt_name":"hari",
"stdnt_ph":9963930865,
"stdnt_mail":"algorithm.class@gmail.com",
"stdnt_course":"Java"
}
sboda@Sriharis-MacBook-Pro enquiry % python3
Python 3.8.5 (v3.8.5:580fbb018f, Jul 20 2020, 12:11:27)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r1 = requests.get("http://127.0.0.1:8000/student/rest/")
>>> print(r1.text)
[{"name":"xyr","ph":8876596787,"course":"python"}]
>>> print(r1.status_code)
200
>>> print(r1.headers)
{'Date': 'Tue, 24 Aug 2021 02:08:42 GMT', 'Server': 'WSGIServer/0.2 CPython/3.8.5', 'Content-Type': 'application/json', 'Vary': 'Accept, Cookie', 'Allow': 'GET, POST, HEAD, OPTIONS', 'X-Frame-Options': 'DENY', 'Content-Length': '50', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin'}
>>> print(r1.json())
[{'name': 'xyr', 'ph': 8876596787, 'course': 'python'}]
>>>
###############################
Create serializer.py in myapp
1 student/serializer.py
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
#fields=("name","mail","course")
fields='__all__'
2. vi student/views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Student
from .serializers import StudentSerializer
# List all students or add new student into DB
class StudentList(APIView):
# # List all students
def get(self,request):
stdnts=Student.objects.all()
# Convert all objects into serialized data
serializer=StudentSerializer(stdnts,many=True)
# Return serialized data
return Response(serializer.data)
#add new student into DB
def post(self,request):
pass
3. mywebsite/student/urls.py
from student import views
from django.urls import path,include
#from . import views
from rest_framework.urlpatterns import format_suffix_patterns
from django.contrib import admin
urlpatterns = [
path('admin/', admin.site.urls),
# path('display/', views.hello,name='hello'),
path('myapp/', include('myapp.urls')),
#path('student/', include('student.urls')),
path('student/',views.StudentList.as_view() ),
]
urlpatterns= format_suffix_patterns(urlpatterns)
4. mywebsite/admin.py
# Register new app with admin
from django.contrib import admin
# Register your models here.
# Register your models here.
from .models import Student
admin.site.register(Student)
##########################################
D:\lab\batch31\myproject>python manage.py shell
>> from student.serializers import StudentSerializer
>>> from student.models import Student>> d={'name':'xyz','mail':'x@gmail.com','course':'Java','phonenumber':987766545567}
>>> new= StudentSerializer(data=d)
>>> new.initial_data
{'name': 'xyz', 'mail': 'x@gmail.com', 'course': 'Java', 'phonenumber': 987766545567}
>>> new.is_valid()
True
>>> new.save()
<Student: xyz987766545567Java>
>>> o= Student.objects.all().last()
>>> print(o)
xyz987766545567Java
>>>
>> from myapp.serializers import stdntSerializer
>>> from myapp.models import stdnt
>>> d={'name':'xyz','email':'x@gmail.com','course':'Java','ph':987766545567}
>>> new= stdntSerializer(data=d)
>>> new.initial_data
{'name': 'xyz', 'email': 'x@gmail.com', 'course': 'Java', 'ph': 987766545567}
>>> new.is_valid()
True
>>> new.save()
<stdnt: xyz987766545567x@gmail.comJava>
>>> o= stdnt.objects.all().last()
>>> print(o)
xyz987766545567x@gmail.comJava
#################################
Views.py
# Create your views here.
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import StudentSerializer
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from rest_framework import status
from rest_framework.decorators import api_view
# List all students or add new student into DB
class StudentList(APIView):
# # List all students
def get(self,request):
stdnts=Student.objects.all()
# Convert all objects into serialized data
serializer=StudentSerializer(stdnts,many=True)
# Return serialized data
return Response(serializer.data)
#add new student into DB
def post(self,request):
pass
@api_view(['GET', 'PUT', 'DELETE'])
def rest_crud(request, pk):
"""
Retrieve, update or delete a code snippet.
"""
try:
stdnt = Student.objects.get(pk=pk)
print("pk:",pk)
print(stdnt)
except Student.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = StudentSerializer(stdnt)
print(serializer.data)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = StudentSerializer(stdnt, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
stdnt.delete()
return HttpResponse(status=204)
myapp/serializers.py
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model=Student
fields=("stdnt_name","stdnt_mail","stdnt_course")
#fields='__all__'
myapp/models.py
class Student(models.Model):
stdnt_name = models.CharField(max_length = 20)
stdnt_mail= models.CharField(max_length = 50)
stdnt_course = models.CharField(max_length = 50)
stdnt_ph = models.IntegerField()
def __str__(self): # What to be displayed when Dreamreal.objects.all() is called
s="name:"+self.stdnt_name+" "+"mail:"+self.stdnt_mail+" "+"Course:"+self.stdnt_course+"Ph:"+str(self.stdnt_ph)
return s
myapp/urls.py
from django.contrib import admin
from django.urls import path,re_path,include
from . import views
from django.views.generic import TemplateView
urlpatterns = [
path('', views.hello,name='hello' ),
re_path('display(\d+)', views.hello2,name='id'),
re_path('date(\d+)', views.hello3,name='id'),
re_path(r'^connection/',TemplateView.as_view(template_name = 'login.html')),
re_path(r'^login/', views.login, name = 'login'),
re_path("register", views.register, name="register"),
#re_path(r'^get/',TemplateView.as_view(template_name = 'contact.html')),
re_path("get_name", views.get_name, name="get_name"),
re_path("post", views.post, name="post"),
re_path("save", views.save, name="save"),
re_path("boot", views.boot, name="boot"),
re_path('rest/',views.StudentList.as_view() ),
re_path('rest_crud/(\d+)/',views.rest_crud, name="pk" ),
]
POST/ UPDATE data
{
"stdnt_name":"hari",
"stdnt_ph":9963930865,
"stdnt_mail":"algorithm.class@gmail.com",
"stdnt_course":"Java"
}
Views.py
@api_view(['GET'])
def apiOverview(request):
api_urls = {
'List':'/studentList/',
'Detail View':'/studentDetail/<str:pk>/',
'Create':'/studentCreate/',
'Update':'/studentUpdate/<str:pk>/',
'Delete':'/studentDelete/<str:pk>/',
}
return Response(api_urls)
@api_view(['GET'])
def studentList(request):
stdnts = Student.objects.all().order_by('-id')
serializer = StudentSerializer(stdnts, many=True)
return Response(serializer.data)
@api_view(['GET'])
def studentDetail(request, pk):
stdnts = Student.objects.get(id=pk)
serializer = StudentSerializer(stdnts, many=False)
return Response(serializer.data)
@api_view(['POST'])
def studentCreate(request):
serializer = StudentSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['POST'])
def studentUpdate(request, pk):
stdnt = Student.objects.get(id=pk)
serializer = StudentSerializer(instance=stdnt, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@api_view(['DELETE'])
def studentDelete(request, pk):
task = Student.objects.get(id=pk)
task.delete()
return Response('Item succsesfully delete!')
urls.py
re_path('rest/',views.StudentList.as_view() ),
re_path('rest_crud/studentList',views.studentList, name="studentList" ),
re_path('rest_crud/studentdetail/(\d+)/',views.studentDetail, name="studentDetail" ),
re_path('rest_crud/studentcreate/',views.studentCreate, name="studentCreate" ),
re_path('rest_crud/studentupdate/(\d+)/',views.studentUpdate, name="studentUpdate" ),
re_path('rest_crud/studentdelete/(\d+)/',views.studentDelete, name="studentDelete" ),
#re_path('rest_crud/',views.apiOverview, name="overview" ),