Decoupling the development of an application into the frontend and the backend is a common architectural implementation in modern app development. With the frontend and backend decoupled, there needs to be a communication middleware that will allow data exchange between these components. This is where application programming interfaces (APIs) come in.
This guide explores API development in REST using Django, which already has a package for REST API development called Django Rest Framework (DRF). The guide assumes you have a basic understanding of APIs and Django web framework and at least intermediate-level proficiency in Python.
An introductory guide on Django can be found here.
The Django Rest Framework is a third-party package that empowers a Django app with REST API capabilities.
To install the package, run the command:
pip install django-rest-framework
This will be a Django app that displays data from the default Sqlite3 database. The data is a list of countries and their currency names.
Fire up a new Django project by running this command.
django-admin startproject countries
Next, create an app and name it currency_country using this command.
python3 manage.py startapp currency_country
The app is now set up. What remains is to develop the country model, the DRF API resources, and provide URLs to the API resources.
The code block below shows the model and what fields make up the database table.
Copy the code block into the
1 2 3 4 5 6 7 8 9
from django.db import models class Country(models.Model): country_name = models.CharField(max_length=20) local_currency = models.CharField(max_length=20) added_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.country_name
The model needs data. To add the data, access the admin panel that requires superuser access. The next step is to create a superuser account using the following command.
python manage.py createsuperuser
This will be an interactive process where you will give essential details and register your user.
For the app and model to be visible, they need to be registered with the Django project and
To register the app and rest framework, a third-party app, add their names to the list of installed apps in
Copy the list below to your
settings.py and replace the existing list.
1 2 3 4 5 6 7 8 9 10
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'currency_country', "rest_framework", ]
To ensure the
Country model is visible on the admin panel, register it in the
Add the code block below to your
1 2 3
from django.contrib import admin from .models import Country admin.site.register(Country)
DRF serializers convert Django data types, such as querysets, into a format that
can be rendered into JSON or XML.
For this app, you only need to create the
In the currency_country app, create a file named
serializers.py and add the code block below.
1 2 3 4 5 6 7 8
from rest_framework import serializers from .models import Country class CountrySerializer(serializers.ModelSerializer): class Meta: model = Country # this is the model that is being serialized fields = ('country_name', 'local_currency')
To service a
POST request, you need a view that will return all countries in a serialized fashion.
To achieve this, create a view within the
views.py file and add the view that will return all countries, serialized.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Country from .serializers import CountrySerializer @api_view(['GET', 'POST']) def country(request): if request.method == 'GET': # user requesting data snippets = Country.objects.all() serializer = CountrySerializer(snippets, many=True) return Response(serializer.data) elif request.method == 'POST': # user posting data serializer = CountrySerializer(data=request.data) if serializer.is_valid(): serializer.save() # save to db return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
To configure the URL, configure the main project's
urls.py file to direct any traffic to the currency_country app using the
path function, as in the codeblock below.
1 2 3 4 5 6 7
from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('currency_country.urls')), ]
Next, create a
urls.py file and, using the
path, direct the traffic to your view function.
1 2 3 4 5 6 7
from django.urls import path from .views import country urlpatterns = [ path('country/', country, name="countries") ]
When all has been set up, the final step is migrating the changes and running the server. To make migrations, run the command:
python manage.py makemigrations
To migrate the model changes into the default database, run the command:
python manage.py migrate
To start the server and run the app, run the command:
python manage.py runserver
Because Django is a popular web development framework and the current architecture of most applications is decoupled, API development in Django is a paramount skill. It can be applied in job positions such as backend developer, API/middleware developer, and full-stack developer.
To further build on your knowledge of Django Rest Framework, explore API concepts such as: