Django REST framework
Request, Response, status, wrapper api views and format suffixes:
Request objects:
Django rest
framework provides Request module which is an extension for HttpRequest. The
main functionality of Request object is request.data which is useful to work
with API.
request.data
handles attribute data, POST, PUT and also PATCH methods
Response objects:
Django rest
framework provides Response module which is an extension for TemplateResponse. And it takes unrendered content and
determines the content type to return to the client.
return Response(data)
status codes:
REST
framework has the status module and it provides various http status codes for
each status which are more readable such as
HTTP_400_BAD_REQUEST
HTTP_404_NOT_FOUND
Wrapping API views:
Django rest
framework provides two wrapper api views
@api_view
decorator for functional based views
APIView class
for class based views
These
wrapper views make sure you receive Request objects in a view and adding content to Response objects.
Adding format suffixes to
URLs:
Response
objects return single content type as client required. Using format suffixes we
can explicitly provide required format by adding format keyword to the views as
fallows
First update
urls.py by adding format_suffix_patterns to the existing URLs.
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from catalogapp import views
urlpatterns = [
path('', views.index, name='index'),
path('books/', views.book_list_view, name='book_list_view'),
path('book/<int:pk>', views.book_detail, name='book_detail'),
]
urlpatterns = format_suffix_patterns(urlpatterns)
now update
views with above all building blocks
from catalogapp.models import Book
from catalogapp.serializers import BookSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
@api_view(['GET', 'POST'])
def book_list_view(request, format=None):
if request.method == 'GET':
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
now API can API will be able to handle URLs such as http://127.0.0.1:8000/catalogapp/books.json
GET /catalogapp/books/
HTTP 200 OK
Allow: POST, GET, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 5,
"title": "The Name of the
Wind",
"author": 6,
"summary": "Told in Kvothe's own
voice, this is the tale of the magically gifted young man who grows to be the
most notorious wizard his world has ever seen.",
"isbn": "9780756404079",
"genre": [
5
],
"language": 5
},
{
"id": 6,
"title": "The Wise Man's
Fear",
"author": 7,
"summary": "Told in Kvothe's own
voice, this is the tale of the magically gifted young man who grows to be the
most notorious wizard his world has ever seen.",
"isbn": "9780756404080",
"genre": [
6
],
"language": 5
},
{
"id": 7,
"title": "The Duelling
Machine",
"author": 8,
"summary": "The dueling machine
helps keep peace throughout the universe until a terrestrial power devises a
telepathic means of controlling the machine thus jeopardizing the security of
all solar systems",
"isbn": "978-003081491",
"genre": [
7
],
"language": 6
},
{
"id": 4,
"title": "White Lines",
"author": 4,
"summary": "Blow, candy, Charlie,
coke, go, ice, rock, snow, crack. Whatever you call it, thrill seekers have
surrendered to cocaine's siren call, paid their toll, and sold their
souls",
"isbn": "9781560253785",
"genre": [
8
],
"language": 4
},
{
"id": 1,
"title": "African Folktales",
"author": 1,
"summary": "Nearly 100 stories from
over 40 tribe-related myths of creation, tales of epic deeds, ghost stories and
tales set in both the animal and human realms.",
"isbn": "9780394721170",
"genre": [
1
],
"language": 1
},
{
"id": 3,
"title": "Touch",
"author": 3,
"summary": "Kyle Kalke, an
astronomer since childhood, a high school \"science nerd,\" falls in
love with flamboyant, outspoken, openhearted Zoe, who—astonishingly—loves him
back",
"isbn": "9780822220558",
"genre": [
9
],
"language": 3
},
No comments:
Post a Comment