Serialize data — User Auth with REST API in Django Part 2

Antonio Caballes
5 min readFeb 10, 2022

--

Welcome to part 2!

Postman
Web

I presume that you’ve accomplished the first part which is the main backbone of part 2. For this tutorial, we are going to display data using REST API in web and Postman Platform. On top of that, we should identify the user trying to access our data in which they should be authenticated. Let’s start!

Before we proceed on the API, I want to add the relationship diagram between our Project model and Profile model. It can be seen that each profile might have multiple Projects. As a result, what should be the relationship of both models?

In the projects/models.py and users/models.py you should add the following code.

users/models.py

# users/models.py ----------class Profile(models.Model):
username = models.CharField(max_length=200, blank=True, null=True)

projects/models.py

# projects/models.py ---------from users.models import Profiledef Projects(models.model):# add owner which has been tagged as a ForeignKey    owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL)
...

Then run the migration. (makemigrations & migrate)

API

We are now going install Django Rest Framework — Link. But before that, I want you to read the documentation first. Take note, don’t install the Django rest framework just yet because I will show you how to setup the folders in our project.

Create a new directory called “api” in the root directory.

To make this a module, follow the file hierarchy as well as their codes.

api/
__init__.py
serializers.py
urls.py
views.py
myrestapi/urls.py, api/views.py & api/urls.py respectively

serializers.py ←- keep this file empty at this point.

Before you move on to the next step, make sure your application is running. To check, run python3 manage.py runserver then enter this url in your browser -> http://127.0.0.1:8000/api/

You should see the following routes

Install Django REST Framework

Installation

Enter pip install djangorestframework. Then check your virtualenv if you’ve acquired the djangorestframework package.

In your settings.py add rest_framework.

INSTALLED_APPS = [
'rest_framework',
]

Again, in the api/views.py (we need to enhance our code here)

We remove the JsonResponse and changed it to Response. In addition, we do not need the safe=False in the second parameter of Response.

💡Good read!!! → Link

  • api_view
  • Response
from rest_framework.decorators import api_view
from rest_framework.response import Response
from projects.models import Project
@api_view(['GET'])
def getRoutes(request):
routes = [
{'GET': 'api/projects'},
{'POST': 'api/users/token'}
]
return Response(routes)

This is it! Let us check on our API route.

Enter http://127.0.0.1:8000/api/🚀

Moving forward to the http://127.0.0.1:8000/api/projects”. It is pretty obvious that this route will give us a list of projects.

Firstly, we need to fix our serializers.

💡WHAT IS A SERIALIZER???

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. → 🔗https://www.geeksforgeeks.org/serializers-django-rest-framework/

In our serializers.py

from rest_framework import serializers
from projects.models import Project
class ProjectSerializer(serializers.ModelSerializer):class Meta:
model = Project
fields = '__all__'

We will call this function to make our data readable. So set this aside, don’t let this code bother you at this moment.

Secondly, in the views.py file. Create a new function called getProjects.

Next is to include this function in our api/urls.py. Add the code below in the list.

path('projects/', views.getProjects),

Visit → http://127.0.0.1:8000/api/projects

What happened? The data that we are trying display is not serializable. Here, we need to serialize our data. Remember, we made a function to make our data readable. Check your serializers.py

# serializers.pyfrom rest_framework import serializers
from projects.models import Project
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = '__all__'

Looking at the details, we imported the serializers and the Project model. The intention is to serialize the data we get in the Project model.

Under the class 🔗Meta we have two section the model and fields. In this portion, we selected Project and we want to display all fields inside the Project model.

How to implement this in our api/views.py

# import the serializer that you've made
from .serializers import ProjectSerializer
# serialize the object --> projects
@api_view(['GET'])
def getProjects(request):
projects = Project.objects.all()
serialize = ProjectSerializer(projects, many=True)
return Response(serialize.data)

Result 🚀

User Auth with REST API in Django — Part 3 — user authentication

Link

Anton Caballes is a student, software developer, and cybersecurity enthusiast. He has a Bachelor’s degree in Information and Communications Technology from San Beda University and is currently pursuing a Master’s in Information Technology at King’s Own Institute Sydney. Check out his work and learning on his personal website and Medium page at https://medium.com/@antonraphaelcaballes. Connect with Anton on LinkedIn to learn more about his achievements and future endeavors.

--

--