M.Ark
Posted on April 3, 2022
Django and Django REST Framework handles, properly, most of the complexity involved with web APIs.
Once we have created a python Django application as shown HERE. Now let’s add an API to it!
We first install django-rest frameworkfrom our command line by running the command below
pipenv install djangorestframework~=3.11.0
Next, we Add rest_framework to the INSTALLED_APPS config in our config/settings.py file. So as to avoid confusion from the local apps and the third parties, I like doing as shown below.
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 3rd party
'rest_framework',
# Local
'books',
]
Our API will expose a single endpoint that lists out all books in JSON format. We will need a new URL route, a new view, and a new serializer file to handle that.
Let’s first create a new api app.
From our terminal;
python manage.py startapp api
And lets add to settings file;
INSTALLED_APPS = [
# Local
'books.apps.BooksConfig',
'api.apps.ApiConfig', # new
# 3rd party
'rest_framework',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
The api app will not have its own database models so there is no need to create a migration file and run migrate to update the database.
URLs
At the project-level we need to include the api app and configure its URL route, which will be api/
path('api/', include('api.urls')),
from our api app, we create a urls.py file by running the commnand below;
touch api/urls.py
Our url file will have the following
# api/urls.py
from django.urls import path
from .views import BookAPIView
urlpatterns = [
path('', BookAPIView.as_view()),
]
All is set for our api urls file, lets proceed to create views;
Views
We are going to create views.py file which relies on Django REST Framework’s built-in generic class views.
In our views.py file, we are going to update as follows
from rest_framework import generics
from books.models import Book
from .serializers import BookSerializer
class BookAPIView(generics.ListAPIView):
queryset = Book.objects.all()
serializer_class = BookSerializer
Explanation of our views code;
On the top lines we import Django REST Framework’s generics class of views, the models from our books app, and serializers from our api app.(We are going to create our serializer in the next step)
We then create a BookAPIView that uses ListAPIView to create a read-only endpoint for all book instances.
Lets Create our serializers
Serializers
In a nutshell, a serializer translates data into a format that is easy to consume over the internet, typically JSON, and is displayed at an API endpoint.
We are going to create a serializer with Django REST Framework and convert Django models to JSON.
Make a serializers.py file within our api app.
From our command line;
touch api/serializers.py
Our serializers.py file will have this content;
# api/serializers.py
from rest_framework import serializers
from books.models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('title', 'subtitle', 'author', 'isbn')
We import Django REST Framework’s serializers class and the Book model from our books app.
We extend Django REST Framework’s ModelSerializer into a BookSerializer class that specifies our database model Book and the database fields we wish to expose: title, subtitle, author, and isbn.
Lets check our API endpoint how it looks like by starting our server and on our browser lets run this URL;
http://127.0.0.1:8000/api/
With the local server still running in the first command line console, navigate to our API endpoint in the web browser at http://127.0.0.1:8000/api/.
To access our api we can use Postman or use Insomnia and we shall be able to see the books and add or update our books.
Posted on April 3, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.