# Topic covered
* Request Object
* Response Object
* DRF provides two wrappers to write API views
* Function based views - @api_view
* Class based views - APIView
* Function based views - @api_view
Request Object
REST framework introduces a Request object that extends the regular HttpRequest, and
provides more flexible request parsing.
The core functionality of the Request object is the request.data attribute,
which is similar to request.POST, but more useful for working with Web APIs.
- request.POST
- Only handles
form data. - Only works for
'POST' method.
- Only handles
- request.data
- Handles arbitrary data.
- Works for ‘POST’, ‘PUT’ and ‘PATCH’ methods.
Response Object
REST framework also introduces a Response object, which is a type of TemplateResponse that takes unrendered content and uses content negotiation to determine the correct content type to return to the client.
- return Response(data)
- Renders to content type as requested by the client
DRF providestwo wrappers to write API views.
- @api_view
- The
@api_viewdecorator for working withfunction based views. - from rest_framework.decorators import api_view
- The
- APIView
- The
APIViewclass for working withclass-based views. - from rest_framework.views import APIView
- The
Browsable API
Django REST Framework supports generating human-friendly HTML output for each resource when the HTML format is requested.
These pages allow for easy browsing of resources,
as well as forms for submitting data to the resources using POST, PUT, and DELETE.
https://www.django-rest-framework.org/api-guide/renderers/#browsableapirenderer
Function based views
# snippets/views.py
@api_view(['GET', 'POST'])
def snippet_list(request, format=None):
if request.method == 'GET':
...
return Response(serializer.data)
elif request.method == 'POST':
serializer = SnippetSerializer(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)
@api_view(['GET', 'PUT', 'DELETE'])
def snippet_detail(request, pk, format=None):
if request.method == 'GET': # GET/PUT/DELETE
....
More
- request
- request used here are not Django obj it is Django-rest obj
- status=status.HTTP_404_NOT_FOUND
- can use “404” directly
- PUT VS PATCH
- In request.method == ‘PUT’
- We need to
pass all fields - SnippetSerializer(snippet, data=request.data)
- We need to
- But in request.method == ‘PATCH’
- We
don't needto pass all fields - SnippetSerializer(snippet, data=request.data, partial=True)
- We
- In request.method == ‘PUT’