Django Rest Framework Serialization Tutorial Part 2

Requirements

In order to complete this tutorial you need to have completed part 1 of this tutorial Django Rest Framework Serialization Tutorial Part 1.

Objective

By the end of this tutorial you would have created a basic serialization API that you can use to serialize and deserialize data using curl.

Steps

We need to create views that can use our serializer class we have created.

  • Add the following scripts into your views.py file:
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from .serializers import DataRowSerializers

class JSONResponse(HttpResponse):
"""
An HttpResponse that renders its content into JSON.
"""
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)

@csrf_exempt
def datarow_list(request):
"""
List all datarow, or create a new datarow.
"""
if request.method =='GET':
datarow = DataRow.objects.all()
serializer = DataRowSerializers(datarow, many=True)
return JSONResponse(serializer.data)

elif request.method=='POST':
data = JSONParser().parse(request)
serializer = DataRowSerializers(data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data, status=201)
return JSONResponse(serializer.errors, status=400)

@csrf_exempt
def datarow_detail(request,pk):
"""
Retrieve, update or delete a DataRow object.
"""
try:
datarow = DataRow.objects.get(pk=pk)
except DataRow.DoesNotExist:
return HttpResponse(status=404)

if request.method == 'GET':
serializer = DataRowSerializers(datarow)
return JSONResponse(serializer.data)

elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = DataRowSerializers(datarow, data=data)
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data)
return JSONResponse(serializer.errors, status=400)

elif request.method == 'DELETE':
datarow.delete()
return HttpResponse(status=204)

The JSONResponse class is an object to be used in the subsequent functions to render the data the app returns in JSON format.

The datarow_list function enables a user to get a list of all DataRow objects as well as insert DataRow data into the app.

The datarow_detail function enables a user to retrieve, update or delete a specific DataRow object by providing the primary key (pk).

Next we need to adjust the data_entry.urls.py file to let the app know which view method to be called when a user goes to a particular url. Add the following lines into the urlpatterns variable:

url(r'^datarows/$',views.datarow_list),
url(r'^datarows/(?P<pk>[0-9]+)/$', views.datarow_detail),

Now we can test our new API using curl:

# List all DataRow objects
curl [docker-machine ip]:8000/datarows/
# [{"id":1,"date":"2017-02-06","gender":"M","favorite_number":5},{"id":2,"date":"2017-02-04","gender":"F","favorite_number":4152},{"id":6,"date":"2017-02-07","gender":"F","favorite_number":321},{"id":7,"date":"2016-03-21","gender":"F","favorite_number":123454321},{"id":8,"date":"2000-01-01","gender":"F","favorite_number":246},{"id":9,"date":"1999-12-31","gender":"M","favorite_number":789}]
# NOTE: You may get something different to this.

# Retrieve a specific DataRow object
curl [docker-machine ip]:8000/datarows/2/
# {"id":2,"date":"2017-02-04","gender":"F","favorite_number":4152}
# NOTE: You may get something different to this.

Conclusion

You have now created a basic serialization API that enables you to get all of your DataRow objects. This is not a perfect API and there are some scenarios that are not handled. For example, malformed JSON will result in a 500 error.

To see how this can be extended to use class based views to keep our code DRY checkout the next tutorial Django Rest Framework Serialization Tutorial Part 3

Subscribe to our mailing list

* indicates required