BUILD THE REST API USING PYTHON DJANGO - PART 2 🐍

devlazar

devlazar

Posted on February 20, 2021

BUILD THE REST API USING PYTHON DJANGO - PART 2 🐍

Table Of Contents
* 🤓INTRODUCTION
* 🧠THE PLAN
* 📚TERMINOLOGY
* 🦄ENTITES AND RELATIONSHIPS
* 🌎CREATE THE PROJECT
* 🙏THANK YOU

🤓 INTRODUCTION

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, Instagram or LinkedIn

🧠 THE PLAN

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
First, let's straight-up our terminology.

📚 TERMINOLOGY

  • 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

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

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
  • After the virtual environment is initialized you should see something like this in your project directory tree Alt Text
  • Open the terminal at the bottom left in the PyCharm IDE
  • Install Django by executing this code
pip install django
Enter fullscreen mode Exit fullscreen mode
  • Install Django Rest Framework by executing the following code
pip install djangorestframework
Enter fullscreen mode Exit fullscreen mode
  • Set up a new project with a single application
django-admin startproject company .
cd company
django-admin startapp API
cd ...
Enter fullscreen mode Exit fullscreen mode

Alt Text

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
Enter fullscreen mode Exit fullscreen mode

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

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'company.API'
]
Enter fullscreen mode Exit fullscreen mode

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

Alt Text

In your settings.py setup the database

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'company',
        'USER': 'postgres',
        'PASSWORD': 'put_postgre_password_here',
        'HOST': 'localhost',
        'PORT': '5432'
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

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']
Enter fullscreen mode Exit fullscreen mode

And add this code to the views.py file:

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]
Enter fullscreen mode Exit fullscreen mode

Inside your urls.py add the following code.

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'))
]
Enter fullscreen mode Exit fullscreen mode

Execute a migration to sync your database for the first time:

python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

You should see something like this in your terminal:
Alt Text

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Alt Text

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

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!

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!
Buy Me a Coffee at ko-fi.com

Have a nice time hacking! 😊

💖 💪 🙅 🚩
devlazar
devlazar

Posted on February 20, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related