If you’ve used a digital device to send and receive information, you’ve used an API. Developers create APIs to enable users to interact with data from their applications.

Creating a REST API is a convenient way to share information. REST APIs have defined standards regulating data sharing between devices. To understand how REST APIs work, you can build one from scratch.

You can use the Django REST framework to build a REST API and use it to display data from a database.

Using Django With a REST API

You can use a REST API to fetch structured data over HTTP. Like many languages and frameworks, Django lets you build your own API and consume others.

You should also have the following pre-installed:

  1. The latest version of python.
  2. The latest version of pip.
  3. Pipenv (although you can use venv instead if you want.)
  4. The latest version of Django.

Once you’ve installed all the essential software, you’re ready to begin.

1. Install Django REST Framework

Django REST framework is a powerful toolkit you can use to build and configure web APIs. Its customizable features make it a popular choice to build REST APIs.

You can install the Django REST framework with the following command:

        pipenv install djangorestframework
    

2. Create a Django App

The following instructions will explain how to create a food application to gather names and descriptions of popular Kenyan foods. The API will fetch requests from a database to enable users to interact with that data.

Django apps come equipped with an SQLite database, so you don't have to install another database.

To create a Django app, first create a project called food with the following command:

        django-admin startproject food 
    

Next, create a Django app called kenyanfood:

        django-admin startapp kenyanfood
    

3. Register the App Project Settings

Register the kenyanfood app in the project settings under the INSTALLED APPS array. If you skip this step, Django will not recognize the app. Also, register the Django REST framework in the same settings:

        # Application definition
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'kenyanfood',
    'rest_framework',
]

4. Register App URLs

Register kenyanfood app URLs in the project urls.py file as illustrated below:

        from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('kenyanfood.urls')),
]

5. Create a View for the API

Create a dummy view in the app’s views.py file, so the app does not throw errors. First, import the Response object and @apiview decorator from the Django REST framework.

Response helps return sterilized data in JSON format while the @apiview displays the API.

        from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.decorators import api_view
 
# Create your views here.
@api_view(['GET'])
def getFood(request):
    return Response()

6. Create a URL Path for the App

Create a URL path for the API view you created. This endpoint displays the kenyanfood data.

        from django.urls import path
from . import views
from django.conf import settings
 
urlpatterns = [
    path('', views.getFood),
    path('post/', views.postFood),
]

7. Create a Model for the App

The app’s model class is called Food. It should look like this:

        from django.db import models
 
# Create your models here.
class Food(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=500)

Register the model in the app admin.py file as shown below:

        from django.contrib import admin
from .models import Food
 
# Register your models here.
admin.site.register(Food)

8. Make Migrations

Next, migrate the app to create tables in the SQLite database. You can do this using the following command:

        python manage.py makemigrations kenyanfood

Next, apply these migrations by running this command:

        python manage.py migrate
    

A successful migration will look like this:

Image shows successfully applied model migrations into database

Successful migrations mean that the database has created tables for the kenyanfood App.

9. Add Data to the Database

Use the Django admin GUI to enter data into the database. Django admin has a great interface to visualize and manage your application's data.

Alternatively, you can use the python shell on the command line to enter data manually into the database. In this guide, you will use the Django admin interface.

Use the following command to set up Django admin:

        python manage.py createsuperuser
    

When prompted, enter your username, email, and password. You can then open the admin page using the link below:

        http://127.0.0.1:8000/admin/
    

You will see the login page:

Image shows the Django admin login page

Once you log in, you will see the Django administration interface with Groups and Users model. These are both for authentication; the Food model is in the section below.

Image shows Django-admin-interface with App models

You can add and delete Food items from the database from the admin page. Add some Kenyan delicacies, such as Ugali, Pilau, and Chai, to the database.

Now that the database has data, create the API

10. Serialize the Model

Serializers convert complex Django models to JSON objects, making data easily read on the API. Serializing makes data more readable on the API.

Create a new file in the app called serializer.py

        from rest_framework import serializers
from .models import Food
 
class FoodSerializer(serializers.ModelSerializer):
    class Meta:
        model=Food
        fields=('name','description')

You import the serializers module from the rest_framework package and create a FoodSerializer class that inherits from the ModelSerializer class.

Next, specify the Food model you want to serialize and the fields you want to add to the API.

11. Update the View

Next, update the API view with the serializer and Food models.

First, define a GET method to retrieve all the data from the database with Food.Objects.all() function. Then serialize the data and returned it as a response in JSON format.

        from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.decorators import api_view
from .models import Food
from .serializer import FoodSerializer
 
# Create your views here.
@api_view(['GET'])
def getFood(request):
    food = Food.objects.all()
    serializer = FoodSerializer(food, many=True)
    return Response(serializer.data)

Then, navigate to the server URL link:

        https://127.0.0.1:8000/
    

You will see the API displaying data from the database:

Image shows how Django-rest framework displays API data on the browser

Congratulations, you have created a REST API!

12. Add Data With POST Method

Test whether you can use the REST API to add data to the database.

First, define a POST method in the view.

        @api_view(['POST'])
def postFood(request):
    serializer = FoodSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

Then, add a path in the app urls.py to create an endpoint for the API POST functionality.

        urlpatterns = [
    path('',views.getFood),
    path('post/',views.postFood),
]

Next, navigate to this URL:

        https://127.0.0.1:8000/post
    

You will see the POST endpoint. Add data to the database in JSON format in the Content section and click the POST button. For example, add a new food item with this structure:

        { "name":"Maziwa mala", "description":"Sour milk" }
    

You will see the data displayed in red in JSON format.

Image show data sent to database via POST endpoint

Now, if you navigate back to the GET endpoint http://127.0.0.1:8000/, you will see the food ‘Maziwa mala,’ and Its description added.

Image shows GET endpoint displaying data in database added from POST endpoint

You now have a REST API that can display and add items to the application. How about experimenting with other CRUD methods? Working with UPDATE and DELETE methods will increase the functionality of your REST API.

How to Create a REST API With Django

You can now create a REST API using Django. First, create an App with a model, Serialize the data, and create a view function. Next, include URL endpoints to visualize the data in JSON format.

Building REST APIs with Django REST framework is a convenient way to share data and give your users a great customer experience.