A RESTFUL API from scratch with Python's DJANGO | With LiverpoolFC 2020/2021 squad list as Endpoint content.
As a Devops Professional, the need to understand and master RESTFUL API's cannot be overemphasized! It is the basic building block of most Applications Architecture especially in the area of Software Design and Engineering. There are numerous frameworks for RESTFUL API's across the different languages. I am familiar with Python's DJANGO and R's Plumber & Pin.
Django is a Monolithic Web framework written in Python, that provides a one stop solution for building Web Products from Dashboards with CRUD requirements.
For this Project, we will be using DJANGO to develop a RESTFUL API providing info on Liverpool Football Clubs Squad list for the 2020/2021 Season. Below are the sequence of steps involved:
STEPS:
1) Install Django Rest Framework
2) Start Top Level Project Folder
3) Create API Project (Second level Project)
4) Define our Applications
5) Create Database & Define Tables based on Project Requirements
6) Commit changes to the Database
7) Run Django Test Page
8) Define our models
9) Define url Requirements in Top Level Project Folder
10) Define and Populate Serializers.py
11) Define and Populate Views.py
12) Define and Populate urls.py
13) Populate our Database with content.
14) Test API Endpoints
DJANGO FRAMEWORK STRUCTURE
Above is the Standard Django framework we intend using for rest of the Article.
STEP 1 | Install Django Rest Framework
STEP 2 | Create Top Level Project Folder
STEP 3 | Create API Project (Second level Project)
Change to the LFCProject. Kindly run the commands below:
The LFCapi contains the bulk of the Django framework and its many components is what we would be using to build our Liverpool API
STEP 4 | Define our Applications
Within the LFCProject/settings.py folder, define the Django Restframework & our LFCapi
STEP 5 | Create Database & Define Tables based on Project Requirements
At this stage, we navigate to LFCapi/models.py and define our Database(SQLite), Tables and Data Types. The class represents the Database while the other variables represent the Tables.
Above we defined two classes which would constitute our Database, while PlayerName & JerseyNumber represent our Database Tables.
STEP 6 | Commit changes to the Database
STEP 7 | Run Django Test Page
SUCCESS!!
STEP 8 | Define our Models
Navigate to LFCapi/admin & register our models.
STEP 9 | Define url Requirements in the LFCProject/urls.py
STEP10 | Define and Populate Serializers.py
Make a file in LFCapi/serializers.py. The role of the serializer is to convert our content to a Json format before it is rendered in a html format.
STEP11 | Define and Populate LFCapi/views.py
In this folder, this is where the heavy lifting is done IMO.
from django.shortcuts import render from django.http import HttpResponse, JsonResponse from rest_framework.parsers import JSONParser from .models import LFCStrikers, LFCDefenders from .serializers import LFCStrikersSerializer,LFCDefendersSerializer #from .models import LFCDefenders #from .serializers import LFCDefendersSerializer def LFCStrikers_list(request): if request.method == 'GET': articles = LFCStrikers.objects.all() serializer = LFCStrikersSerializer(articles, many = True) return JsonResponse(serializer.data, safe = False) elif request.method == 'POST': data ?= JSONParser().parse(request) serializer = LFCStrikersSerializer(data = data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status = 400) def LFCStrikers_detail(request, pk): try: article = LFCStrikers.objects.get(pk = pk) except LFCStrikers.DoesNotExist: return HttpResponse(status = 404) if request.method == 'GET': serializer = LFCStrikersSerializer(article) return JsonResponse(serializer.data) elif request.method == 'PUT': data ?= JSONParser().parse(request) serializer = ArticleSerializer(article, data ?= data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status = 400) elif request.method == 'DELETE': article.delete() return HttpResponse(status = 204) def LFCDefenders_list(request): if request.method == 'GET': articles = LFCDefenders.objects.all() serializer = LFCDefendersSerializer(articles, many = True) return JsonResponse(serializer.data, safe = False) elif request.method == 'POST': data ?= JSONParser().parse(request) serializer = LFCDefendersSerializer(data = data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status = 400) def LFCDefenders_detail(request, pk): try: article = LFCDefenders.objects.get(pk = pk) except LFCDefenders.DoesNotExist: return HttpResponse(status = 404) if request.method == 'GET': serializer = LFCDefendersSerializer(article) return JsonResponse(serializer.data) elif request.method == 'PUT': data ?= JSONParser().parse(request) serializer = ArticleSerializer(article, data ?= data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status = 400) elif request.method == 'DELETE': article.delete() return HttpResponse(status = 204)
In LFCapi/views.py, classes from serializer, models are imported of which classes are defined for GET,PUT, DELETE, UPDATE instances giving custom messages as the case may be. It is also important to mention that we define Primary keys as well. This is so as it enables filter json data by id(By Default is the Primary Key)
STEP12 | Define and Populate LFCapi/urls.py
In this file we imported our classes from LFCapi/views.py. The goal of this script is to define how our url appears on a web browser. All the heavy lifting has been done in the LFCapi/views.py.
STEP 13 | Populate our Database with content
By default, Django uses sqllite as its database. The goal of this step is to populate our already created Database (STEP 5) with content.
root@nosa2k-VirtualBox:/home/nosa2k/LFCProject#python3 manage.py shell from LFCapi.models import LFCDefenders from LFCapi.serializers import LFCDefendersSerializer from rest_framework.renderers import JSONrenderer from rest_framework.renderers import JSONRenderer from rest_framework.parsers import JSONParser a = LFCDefenders(PlayerName = "Virgil_Van_Dijk", JerseyNumber = "4") a.save() a = LFCDefenders(PlayerName = "Andy_Robertson", JerseyNumber = "26") a.save() a = LFCDefenders(PlayerName = "Nathaniel_Phillips", JerseyNumber = "47") a.save() a = LFCDefenders(PlayerName = "Neco_Williams", JerseyNumber = "76") a.save() a = LFCDefenders(PlayerName = "Joe_Gomez", JerseyNumber = "12") a.save() a = LFCDefenders(PlayerName = "Joel_Natip", JerseyNumber = "32") a.save() a = LFCDefenders(PlayerName = "Trent_Alexander-Arnold", JerseyNumber = "66") a.save() a = LFCDefenders(PlayerName = "Kostas_Tsimikas", JerseyNumber = "21") a.save() a = LFCDefenders(PlayerName = "Rhys_Williams", JerseyNumber = "46") a.save() a = LFCDefenders(PlayerName = "Sepp_Van_Den_Berg", JerseyNumber = "72") a.save() exit() #Commit changes to Database root@nosa2k-VirtualBox:/home/nosa2k/LFCProject# python3 manage.py makemigrations No changes detected root@nosa2k-VirtualBox:/home/nosa2k/LFCProject# python3 manage.py migrate Operations to perform: Apply all migrations: LFCapi, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. root@nosa2k-VirtualBox:/home/nosa2k/LFCProject#
Here, we navigate to our Database and populate the tables we defined in (STEP 5) with content. Strikers and Defender Positions were populated.
STEP 14 | Testing our Endpoints...
Here we test our Endpoints with the url paths we defined in STEP 12
Success!!
Using Postman...
For LiverpoolFC Strikers....
Using Postman...
Success!!
We have successfully created a RESTFUL API from scratch using Django Web framework! The API Endpoint produced Liverpool Strikers and Defenders Squadlist for the 2020/2021 Season.
These exposed endpoints could be used to feed developers who could use different languages to develop Applications.
SUMMARY:
Django has a steep learning curve in my opinion. I would rather use R Shiny to develop Dashboards and Applications alongside Docker and Kubernetes to scale in Production. Django shines in my opinion for building RESTFUL API's as its framework has a strong back-end posture very suitable for API's.
REFERENCES:
https://codeloop.org/django-rest-framework-course-for-beginners/ https://www.youtube.com/watch?v=B38aDwUpcFc&feature=emb_logo https://www.django-rest-framework.org/
Django Dev | Student Advocate
3 年Interesting ??