Hello, dear hackers! Welcome to yet another blog article on "Building the REST API with Python Django". I really appreciate your interest in these kinds of articles, and I am really happy that I can help you learn something new.
If you missed the previous article, check it out:
Article No Longer Available
Everything I do in this article and upcoming articles will be pushed to the repository on my GitHub:
To make all routes map into /api/... we will create another file inside our API folder, name it urls.py
Before we proceed with this file, we need to create our serializer and views
π¨π»βπ» SERIALIZERS
Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML, or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.
The serializers in the REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializer class which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.
In our serializers.py add the following code (note that I omitted the code regarding UserSerializer and GroupSerializer):
This means that we will serialize our Model Employee and include all the fields that our model offers.
πβπ¨ VIEWS
Each view we create will handle specific logic and will map the response with the specific route. Let's create our first view, which will get all the data regarding employees.
In your views.py file add the following code:
fromcompany.API.serializersimportUserSerializer,GroupSerializer,EmployeeSerializerfromcompany.API.modelsimportEmployeefromrest_framework.responseimportResponsefromrest_framework.viewsimportAPIViewclassEmployeeList(APIView):"""
List all employees
"""defget(self,request,format=None):employees=Employee.objects.all()serializer=EmployeeSerializer(employees,many=True)returnResponse(serializer.data)
πΊ MAP URL
Before we add some code to the newly created urls.py, go to the urls.py file inside the company folder, and in the urlpatterns block add the following code:
path('api/',include('company.API.urls'))
This part of the code will consider the http://127.0.0.1:8000/api/ - the base URL - but that path will map all the paths inside our newly created urls.py.
Now, we have our Employee serializer and Employee View, we need a specific endpoint that will map our response data.
In the newly created urls.py, add the following code:
Now, we should be ready to get the data from the server (please use your admin panel to add some data for employees before proceeding).
Run the following command:
python manage.py runserver
Click here to see the result in your browser or manually type in your URL bar http://127.0.0.1:8000/api/employee/
Since I have only one record in the database, here is my response:
Congratulations! π You created your first GET request, you could also send the request using the Postman, for now, I will stick to the browser.
1οΈβ£ GET SPECIFIC RECORD
Similarly, when we want to get the specific record by the unique identifier, we define our view that we will name EmployeeDetails, and after that, we map our view to the specific URL.
Here is the view for getting specific Employee record by the unique identifier
classEmployeeDetails(APIView):"""Retrieve an employee instance"""defget_object(self,pk):try:returnEmployee.objects.get(pk=pk)except:raiseHttp404defget(self,request,pk,format=None):employee=self.get_object(pk)serializer=EmployeeSerializer(employee)returnResponse(serializer.data)
As you can see, we are using get_object function where we pass the primary key of an instance we are requesting. We have a try-except block of code, where we determine if such an instance exists, or if it does not, we raise an error. An Http404 error is imported as from django.http import Http404;
Now, we should map our URL, add the following code to the urlpatterns inside the newly created urls.py file.
Ok, we should be ready to retrieve the specific data for a single Employee instance. First, you need a primary key, if you execute http://127.0.0.1:8000/api/employee/ you will see that each employee has an employee_id attribute, copy one of the employee_ids and execute this route https://127.0.0.1:8000/api/employee/paste_your_employee_id_here you should GET a single instance with the specific employee_id you requested.
Here is mine π½
π£ OUTRO
So, we created views for getting all employees' data and for getting a single employee data. The logic is the same for the Project and Sector model. I encourage you to try, and write those views, serializers and urls by yourself, but If you get stuck, you can always look for the solution on my GitHub. In the next article, we will create the POST and PUT methods.
π THANK YOU FOR READING!
Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me!