π REST APIs provide a convenient way to send and receive information.
Recall in our previous project tutorials, we created a Django News app using News API and a Django Weather app using OpenWeather API. We were able to receive and interact with data from those websites to build the applications through the APIs they offered.
Using Django, we can build our APIs. That is exactly what we are going to learn in this tutorial.
Django REST framework is a powerful tool for building web APIs. By building a REST API, we can expose important data to be accessed at a given URL.
For example, we can build a real estate application using the Django REST framework in such a way that other web applications can interact with the data we expose the same way we interacted with the website APIs when building the weather and news websites.
π‘ What’s a REST API?
A REST API (Representational State Transfer Application Programming Interface) is a set of protocols used to build and interact with web services.
It employs standard HTTP methods (GET, POST, PUT, DELETE) to manipulate named resources, which can be accessed via unique URIs (Uniform Resource Identifiers).
Each request is stateless, containing all necessary information, with no context saved on the server between requests.
The server provides a “representation” of the requested resource, often in XML or JSON format. REST APIs aim for a uniform, predictable structure and cacheable responses, facilitating the development of scalable and easily maintainable web services.
In this project, we will create a food application. I believe a good number of us admire African dishes and would love to have a taste. This will be a rare opportunity to get to know some of them. This project will display the names and descriptions of Nigerian dishes.
Users can interact with the data probably to become familiar with Nigerian dishes, and if possible, book one from a nearby African restaurant. Speaking of booking, Iβm learning how to create a booking system and would love to share my knowledge in future tutorials.
Getting Started
To get started building this project, we will have to pass through a boring but important process to set up Django in our system. So, hoping you are using Ubuntu. The steps are as follows:
Step 1: Creating a new folder for the project
mkdir django_project && cd django_project
Step 2: Activate a virtual environment
python3 -m venv .venv . .venv/bin/activate
Step 3: Install Django and Django REST framework
pip install django djangorestframework tzdata
Step 4: Create a requirements.txt
file
pip freeze > requirements.txt
The dot is used to activate the virtual environment. Alternatively, use the source command. Having completed those steps, we can now proceed to create a Django application.
django-admin startproject food . python3 manage.py startapp nigerianFood
The trailing dot this time, indicates the current directory. You should make it a practice of registering the app as soon as it is created. So, letβs do so in the INSTALLED_APPS
array of the settings.py
file.
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # custom app 'nigerianFood', # third-party app 'rest_framework', ]
Notice we add the rest_framework
from the djangorestframework
module. This is a mandatory requirement to use the features.
The Model
We now create a model for the database.
from django.db import models # Create your models here. class Food(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=500)
The Food
class is a simple one with only two fields, the name and description of the food. The CharField
was used because we want short sentences.
Next, we run the migrate
command to apply migrations.
python3 manage.py makemigrations python3 manage.py migrate
The makemigration
command first tells Django of changes made to the database while the migrate
command applies those changes to create a database for the nigerianFood
app.
The Python Shell
While creating a portfolio app in our previous project tutorials, we use the Django admin interface to enter data. But in this project, we will use the Python shell.
Note that the Django admin is the best way to manually enter data to your database. Iβm only using the Python shell for learning purposes, to show you different ways it can be done.
Use this command below to access the Python shell.
python3 manage.py shell
Start by importing your models
>>> from nigerianFood.models import Food
Create an instance of the Food
class, and add some Nigerian foods.
>>> f1 = Food( ... name='Akpu', ... description='A thick staple Nigerian food made from fresh or fermented cassava' ... ) >>> f1.save() >>> f2 = Food( ... name='Pounded Yam', ... description='A stretchy dough made from boiled yams' ... ) >>> f2.save() >>> f3 = Food( ... name='Tuwon Shinkafa', ... description='A thick pudding prepared from local rice' ... ) >>> f3.save() >>> f4 = Food( ... name='Jollof Rice', ... description='One of the most widely consumed food often served with chicken and chilled drinks' ... ) >>> f4.save() >>> f5 = Food( ... name='Egusi Soup', ... description='A soup prepared with ground melon and some other ingredients' ... ) >>> f5.save() >>> f6 = Food( ... name='Pepper Soup', ... description='The most popular type of food in Africa said to have medicinal qualities, made with pepper and some assortments of meat, and often served with beer' ... ) >>> f6.save()
We use the Python shell to create six instances of the Food
class. You can add more Nigerian foods you know. Notice that we save each instance of the class created. This stores the data in the database.
Serializing the Model
Serializing means converting a Django model to a JSON object to make it more readable on the API. Create a serializer.py
file inside the nigerianFood
folder.
from rest_framework import serializers from .models import Food class FoodSerializer(serializers.ModelSerializer): class Meta: model = Food fields = '__all__'
Here, we import the serializer
module from the rest_framework
third-party package we installed earlier. We create a class named FoodSerializer
which inherits from the ModelSerializer
class. This is similar to the way our Food
class inherits from the model.Model
class.
Another class was created. This tells Django which model we want to serialize. Using __all__
indicates that we want the serialization to be done on all the model fields.
Conclusion
In this tutorial on creating a REST API using the Django REST framework, we installed Django and the rest_framework
package. We created a class for our database, and used the Python shell to manually enter some data. Finally, we created a serializer.py
file that will serialize our model.
You can view the code for this part here. In the second part of this tutorial, we will create a CRUD API which will apply the serialization and presents us with JSON objects.
π§βπ» Recommended: How I Created a Calculator App using Django