Django Rest API – From Scratch – Part 2

Let’s serialize our own models
This is the continuation of part 1 of my tutorial series. So, if you haven’t viewed part 1 of the tutorial, then you can find it here: https://nepcodex.com/blog/2019/07/django-rest-api-from-scratch-part-1/
Register
We have already created our todo
app, hence we need to register it in our settings.py
file.
INSTALLED_APPS = [ ... 'rest_framework', 'todo.apps.TodoConfig' ]
Creating own model
Now, we have to define our model which resides in our database. In your todo/models.py
paste the following lines of code:
from django.db import models # Create your models here. class Todo(models.Model): title = models.CharField(max_length=100, help_text='Enter the title of your Todo, try to make it short') description = models.CharField(max_length=255, help_text='Enter what is the todo about and its details') is_completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) class Meta: ordering = ['created'] def __str__(self): return self.title
Finally, you have to migrate the class to the database. You can do it by following lines of code
python manage.py makemigrations
python manage.py migrate
Serializers
We need serializers to get the required json. So, we need to create serializers classes. Therefore, add some lines of code in todo/serializers.py
file
from rest_framework import serializers from .models import Todo class TodoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Todo fields = ['title', 'description', 'is_completed', 'created', 'last_modified']
Views
Let’s write some API views using our new Serializer class. So, open todo/views.py
file
Since, we don’t have csrf_token
in the client apps from where we will POST, therefore, we have to override the csrf_token
. Hence, @csrf_exempt
decorator can be used for this purpose, however, its implementation is different for class.
# from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt # from rest_framework.parsers import JSONParser from .models import Todo from .serializers import TodoSerializer class TodoViewSet(viewsets.ModelViewSet): """ API endpoint that allows todos to be viewed or edited. """ @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(TodoViewSet, self).dispatch(request, *args, **kwargs) queryset = Todo.objects.all() serializer_class = TodoSerializer
URLs
Now, we need to wire the views to our URLs. For that, open tutorial/urls.py
file and addsome lines of code
from todo import views ... router.register(r'todos', views.TodoViewSet)
Testing
Finally, you can test the endpoints using Postman. For that, just paste the code below in your terminal.
You have to add a Content-Type
to the value application/json
. The paste following json
in the body and POST it into http://127.0.0.1:8000/todos/ and Note the trailing slash.
{ "title": "My Todo Title", "description": "My Todo Description" }
Now, you can refresh http://127.0.0.1:8000/todos. Here, you will find your todo posted.
To view individual todo, enter the todo id like below
Summary
Up to this point, what we did can be summarized as:
- Registered the
todo
app. - Created own model
Todo
and migrated to the database. - Implemented serializers for the model
- Provided viewsets for the model
- Registered the route
- Tested in Postman
I hope you have successfully completed till now. You can revise the points it know if anything has missed.