BUILD THE REST API USING PYTHON DJANGO - PART 4 🐍
Tags: javascript, django, programming, python
Published: 2021-02-22 19:11:43

Table Of Contents
        * 🤓[INTRO](#intro)
        * 🔗[URLS](#urls)
        * 👨🏻‍💻[SERIALIZERS](#serializers)
        * 👁‍🗨[VIEWS](#views)
        * 🗺[MAP URL](#maps)
        * 1️⃣[GET SPECIFIC RECORD](#single)
        * 📣[OUTRO](#outro)
        * 🙏[THANK YOU](#thank-you)


## 🤓 INTRO <a name="intro"></a>
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:
{% post https://dev.to/codespresso/build-the-rest-api-using-python-django-part-3-16c %}

Everything I do in this article and upcoming articles will be pushed to the repository on my GitHub:
{% github https://github.com/Dwarf95/PythonDjangoTutorial %}

Today, we are writing methods for GETting all the data from an API as well as GETting the specific record by record id.

Please feel free to connect with me via [Twitter](https://twitter.com/lazar_dev), [Instagram](https://www.instagram.com/codespressoweb/) or [LinkedIn](https://www.linkedin.com/in/lazar-stankovic-44a199177/)

Let's start! 🚀


## 🔗 URLS <a name="urls"></a>
We already have our urls.py inside our company folder. But what we want to achieve is to make our API URLs map as follow:

- http://127.0.0.1:8000/api/ - **BASE URL**
- http://127.0.0.1:8000/api/employee/ - **Return data for all employees in the database**
- http://127.0.0.1:8000/api/employee/:id - **Manipulate specific employee**
- http://127.0.0.1:8000/api/sector/ - **Return data for all sectors in the database**
- http://127.0.0.1:8000/api/sector/:id - **Manipulate specific sector**
- http://127.0.0.1:8000/api/project/ - **Return data for all project in the database**
- http://127.0.0.1:8000/api/project/:id - **Manipulate specific sector**

To make all routes map into /api/... we will create another file inside our API folder, name it urls.py

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0x5ne6azf2l28j5onzl.png)

Before we proceed with this file, we need to create our serializer and views

## 👨🏻‍💻 SERIALIZERS <a name="serializers"></a>
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):
```python
from company.API.models import Employee

class EmployeeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Employee
        fields = '__all__'
```
This means that we will serialize our Model **Employee** and include all the fields that our model offers.

## 👁‍🗨 VIEWS <a name="views"></a>
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:
```python
from company.API.serializers import UserSerializer, GroupSerializer, EmployeeSerializer
from company.API.models import Employee
from rest_framework.response import Response
from rest_framework.views import APIView


class EmployeeList(APIView):
    """
    List all employees
    """
    def get(self, request, format=None):
        employees = Employee.objects.all()
        serializer = EmployeeSerializer(employees, many=True)
        return Response(serializer.data)
```

## 🗺 MAP URL <a name="maps"></a>

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:
```python
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:
```python
from . import views
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns

urlpatterns = [
    path('employee/', views.EmployeeList.as_view(), name="employees")
]

urlpatterns = format_suffix_patterns(urlpatterns)
```
This will map our EmployeeList view response to http://127.0.0.1:8000/api/employee/

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](http://127.0.0.1:8000/api/employee/) 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:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6njmnhqmgpwb1ue55sv.png)

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 <a name="single"></a>
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
```python
class EmployeeDetails(APIView):
    """Retrieve an employee instance"""

    def get_object(self, pk):
        try:
            return Employee.objects.get(pk=pk)
        except:
            raise Http404
    
    def get(self, request, pk, format=None):
        employee = self.get_object(pk)
        serializer = EmployeeSerializer(employee)
        return Response(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.
```python
path('employee/<slug:pk>', views.EmployeeDetails.as_view(), name="employee")
```

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 👽

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s69mooarofwz4opvn3vk.png)

## 📣 OUTRO <a name="outro"></a>
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!<a name="thank-you"></a>

Please leave a comment, tell me about you, about your work, comment your thoughts, connect with me! 

☕ SUPPORT ME AND KEEP ME FOCUSED!
<a href='https://ko-fi.com/Z8Z33D1HJ' target='_blank'><img height='36' style='border:0px;height:36px;' src='https://cdn.ko-fi.com/cdn/kofi4.png?v=2' border='0' alt='Buy Me a Coffee at ko-fi.com' /></a>

Have a nice time hacking! 😊