BUILD THE REST API USING PYTHON DJANGO - PART 2 🐍
Tags: javascript, django, programming, python
Published: 2021-02-20 16:14:22

Table Of Contents
        * 🤓[INTRODUCTION](#intro)
        * 🧠[THE PLAN](#plan)
        * 📚[TERMINOLOGY](#terminology)
        * 🦄[ENTITES AND RELATIONSHIPS](#entities)
        * 🌎[CREATE THE PROJECT](#create)
        * 🙏[THANK YOU](#thank-you)


## 🤓 INTRODUCTION <a name="intro"></a>
Hello, my dear hackers! Welcome, to the second part of the "Building the REST API with Python Django" series. I hope you are all having a great day, today is a big day, we will start **planning** and **implementing** the REST API using Python Django Rest Framework. 


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/)

## 🧠 THE PLAN <a name="plan"></a>
Let me explain the plan. Don't worry, I will provide a visual example too 😎 We are going to build the REST API handling the company data for Employees, Sectors, and Projects! Each employee, sector, and project is described with specific attributes that are usually of some significance to the user consuming the data. Let me show you the diagram, and I will describe each **entity** separately as well as the **relationships** among them.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n9pmdk18brxqna114bgv.jpg)
First, let's straight-up our terminology.

### 📚 TERMINOLOGY <a name="terminology"></a>
- **RELATION** - the table with rows and columns
- **ATTRIBUTE** - named column of the relation
- **ATTRIBUTE DOMAIN** - the set of the allowed values for an attribute
- **CARDINALITY** - Number of data instances (rows) in the relation
- **RELATION KEY** - An attribute or a set of attributes that identify each data instance in a unique manner
- **PRIMARY KEY** - A candidate key which is selected to identify each data instance in a unique manner
- **FOREIGN KEY** - An attribute or a set of attributes getting paired-up with the primary key (candidate key) of some other relation
- **ENTITY INTEGRITY** - non of the primary key's attributes can have the value of NULL - no primary key can be NULL
- **REFERENTIAL INTEGRITY** - Values of the foreign key must be equal by value to the candidate key of the specific data instance in the initial relation, or can have the value of NULL

## 🦄 ENTITES AND RELATIONSHIPS <a name="entities"></a>
Our diagram describes:

**AN EMPLOYEE ENTITY** - Each employee, has **attributes**; The name that is a composite attribute and includes the first name, middle name, and last name. Also, we have, gender, address, salary, and the unique identifier ID.
**THE SECTOR ENTITY** - Name, Location, and a unique identifier.
**THE PROJECT ENTITY** - Name Location and a unique identifier.

**RELATIONSHIP 1** - The relationship between Employee and the Sector. Each employee works in only one sector, and each sector can have many employees.
**RELATIONSHIP 2** - The relationship between Sector and Project. Each sector can be in charge of multiple projects but that specific project gets assigned to the specific sector.
**RELATIONSHIP 3** - The relationship between Employee and the Project. Each employee can work on multiple projects, and each project can have multiple employees working on it.

So, let's get to business and start creating our project! 🚀


## 🌎 CREATE THE PROJECT <a name="create"></a>
We start by creating our project, and we will use the PyCharm GUI to do so.

- Open up the PyCharm
- Click on create the new project - make sure you have the right base interpreter selected
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/flgdgolgf2mgy4bdenhm.png)
- After the virtual environment is initialized you should see something like this in your project directory tree 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ulxg4r75lxc2cgj608xm.png)
- Open the terminal at the bottom left in the PyCharm IDE
- Install Django by executing this code
```
pip install django
```
- Install Django Rest Framework by executing the following code
```
pip install djangorestframework
```
- Set up a new project with a single application
```
django-admin startproject company .
cd company
django-admin startapp API
cd ...
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6bq0zjvxpwh7wind70l.png)

So, we created our **project**, the CompanyProject, and our **application** within the **project** that we named API.

Let's now install the **psycopg2** adapter for the PostgreSQL database.
```
pip install psycopg2
```

Register the rest framework and our application by navigating to the settings.py file and add this to you INSTALLED_APPS.

```python
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'company.API'
]
```

Go to the pgAdmin and create the new database, I will name my database company, you can name yours as you wish.

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

In your settings.py setup the database
```python
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'company',
        'USER': 'postgres',
        'PASSWORD': 'put_postgre_password_here',
        'HOST': 'localhost',
        'PORT': '5432'
    }
}
```

Create serializers.py inside your API directory. Let's create our user serializer and user group serializer. Add this code to your serializers.py file:
```python
from django.contrib.auth.models import User, Group
from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']
```
And add this code to the views.py file:
```python
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from company.API.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]
```

Inside your urls.py add the following code.
```python
from django.urls import include, path
from rest_framework import routers
from company.API import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
```

Execute a migration to sync your database for the first time:
```
python manage.py migrate
```
You should see something like this in your terminal:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/772s2y3qmibhbq4x0qij.png)

Now, let's create the superuser that we will use to login to our administrator panel.
```
python manage.py createsuperuser --email admin@example.com --username admin
```
After executing this line you will have to specify your password, you can change your password any time.

Let's run our project!
```
python manage.py runserver
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ovjpk647zwbhmejx2ru.png)

That is it! 🎉 We created our first project, go to your browser, redirect to HTTP://127.0.0.1:8000/ and you will get your browsable API.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kz0nwnhyfvgzbjiklp7x.png)

That is it for now, in our next chapter we will create our models for our company API and views.

Stay tuned! 🚀

# 🙏 THANK YOU FOR READING!<a name="thank-you"></a>
References:
School notes...
School books...

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! 😊