REST API With Django Rest Framework

REST API With Django Rest Framework

ยท

9 min read

Introduction

Django-rest-framework is a powerful and flexible toolkit for building Web APIs. In this tutorial, we will take a ride building our own API, and trust me doing so in Django is super easy. so sit back and grab a cup of your favorite drink and let's role.๐Ÿฅ‚๐Ÿฅ‚

Before we get into coding, it's quite productive to understand some concepts about REST APIs.

What is an API?

The acronym API stands for Application Programming Interface and it's a set of rules that allow programs or machines to communicate with each other and perform some specific task. The developer creates the API on the server and allows the client to communicate with the server by making a request to the server and in turn awaits a response.

REST API

REST stands for Representational State Transfer. it is a set of rules developers follow when building APIs. REST API delivers data in the lightweight JSON format. Most public APIs use this data format because of its fast performance, dependability, and ability to scale by reusing modular components without affecting the system as a whole.

REST API is a standard way to provide data to other applications or programs. These applications can then use the data however they want and sometimes the API also allows the applications to make changes to the data. Some key options for the REST API request include GET, POST, PUT, PATCH, DELETE

Why Django REST Framework?

Some of the reasons why you might want to use the Django rest-framework includes;

  • The Browsable API which is a huge usability win for developers allows you to run and debug your APIs right in the browser.

  • Built-in Authentication policies such as OAuth1a and OAuth2.

  • Easy serialization that supports both ORM and non-ORM databases. serialization is the process of converting data inputs or objects into python native objects and vice versa (deserialization)

  • Highly customizable
  • Extensive documentation and great community support.

going forward! We will build a simple movie reviews api.

steps

  1. Setup Django
  2. Create a model in the database that will we manage through the Object Relational Mapper (ORM)
  3. Setup Django Rest-Framework (DRF)
  4. Serialization
  5. Create URL endpoints to view the serialized data

the code for this tutorial is available at https://github.com/itslogique/drf-article-code

1. Set up Django

Before we go on, make sure you have python installed so that you can use pip to access other packages as we would do in this tutorial. Next stop we need to install Django but before that let's consider creating a virtual environment so as to package all dependencies for our project in isolation. let's create a folder called movies_api.

$ mkdir movies_api 
cd movies_api

1.1 virtual environment

We can create a virtual environment with the following command.

# windows 
python -m venv space 
# mac 
 python3 -m venv space

noticed I called the environment space. To use the virtual environment, we need to activate it and the following command will do it.

# windows 
source /space/Scripts/activate 
# mac 
source /space/bin/activate

Now we can install Django

pip install django

1.2 Creating a new Django project

django-admin startproject mysite .

Noticed the period sign after the mysite? meaning the folder should be created right on the current directory and not in a new folder entirely.

Next, let's create a movies_api app

python manage.py startapp movies_api

1.3 Register movies_api app

Now before we can successfully use the movies_api app in sync with django, we need to make django aware of the newly created app by adding the app details to the INSTALLED_APPS section of the mysite/settings.py file

INSTALLED_APPS = [
# Every other setting here remain unchanged 
# Add the command below to register app  
'movies_api.apps.MoviesApiConfig',
]

1.4 Database Migration

Django allows you to create database models using python. Whenever we create or make changes to the models we need to tell Django to migrate the changes to the database. The Django ORM handles all the SQL queries such as CREATE-TABLE INSERT etc. We don't need to bother about explicitly writing the SQL commands. Running the Django server in the current state of our code we will get the following message....

unapplied migrations .png

The above message is not an error. What happened is that Django ships with some built-in models and a sqlite3 database. In order to work with the database, we need to migrate the models into the database with the following command.

python manage.py makemigrations

the above command is responsible for creating new migrations based on the changes you have made to the models then followed by python manage.py migrate which handles applying and unapplying the migrations. Since we have not created any models yet we just need the next command

python manage.py migrate

After running the above two commands we should get a message like this.

2migrations.png

1.5 Create Super User

Next stop, let's create an admin user on the system that we can use to manage other actions. key in the following command.

superuser.png

Let's verify that Django is working perfectly fine by starting the Django local server.

localserver.png

And visit localhost:8000 to see the Django start page. HOORAY! We've got Django nicely setup. ๐Ÿฅ‚๐Ÿฅ‚

2.0 Create a Model

Remember we said django comes with some pre-built model right. Now let's create our own model. And we will do this in the movies_api/models.py so jump into that file.

# in movies_api/models.py
from django.db import models 

class Movie(models.Model):
"""Movie review database model"""
movie_title = models.CharField(max_length=100)
main_actors = models.CharField(max_length=255)
description = models.CharField(max_length=255)
genre = models.CharField(max_length=255)
rate = models.CharField(max_length=5)

  def __str__(self):
      return self.movie_title

The movie_title, main_actors, description, genre, and rate are character fields that we can use to store strings. The __str__ method tells django how to represent an instance of the model anytime it is created.

2.1 Register the Movie Model

We need to register the Movie model with the admin so as to have it showing on the admin dashboard area. open movies_api/admin.py and add the following command

from django.contrib import admin
from .models import Movie

admin.site.register(Movie)

2.2 Migration

We've just created and registered a model, now let's migrate it to the database using the python manage.py makemigrations to create the new migration and python manage.py migrate to apply the migrations.

model migration.png

Next, let's run the server using python manage.py runserver and visit localhost:8000/admin and log in using our superuser credentials to see our newly created model.

model view.png

while we are here, let's create some movie reviews. Click on Add Movie to create some movie reviews.

added reviews.png

3.0 Django Rest Framework

To work with django rest-framework we need to have it installed. the next command helps us do so.

pip install djangorestframework

let's tell Django about it by registering it to the INSTALLLED_APPS section of the mysite/settings.py file.

INSTALLED_APPS = [ 
# all setting here remain unchanged 
# add the next command 
'rest_framework',
]

next, we need to convert our model instances to python datatypes that can be easily rendered into JSON, XML which are understandable by Javascript and other frameworks (serialization).

4.0 Serialization

serialization is the process of converting complex querysets or model instances to JSON or XML. serialization also specifies what fields should be present in the JSON representation of the model. The JSON representation of the API allows users to parse the API even if they are not using python. Also, when users make a POST, PUT, PATCH request to our API, the serializer also converts the data from JSON to a model instance after validating the incoming data through a process called deserialization. let's create a new file called serializers.py in the movies_api app.

we will do the following in the new file

  • Import serializers module from rest_framework
  • import Movie model
  • create a Meta class that connects the serializer with the Model
# movies_api/serializers.py 

from rest_framework import serializers
from .models import Movie

class MovieSerializer(serializers.HyperlinkedModelSerializer):
  """Serializes a new movie model"""
  class Meta:
  model = Movie
  fields = ['id', 'movie_title', 'main_actors',
              'description', 'genre', 'rate']

5.0 Rendering the data

In order to display the data, we need to create the endpoints by wiring up the urls and views

5.1 Views

let's start with creating the view to render the different instances of the Movie model.

from django.shortcuts import render
# import local data
from .models import Movie
from .serializers import MovieSerializer
# import viewsets
from rest_framework import viewsets


class MovieViewSet(viewsets.ModelViewSet):
  """Renders the Movie model instances"""
  queryset = Movie.objects.all().order_by('movie_title')
  serializer_class = MovieSerializer

when working with Django models, by just specifying the queryset and serializer_class the ModelViewSet automatically makes all the CRUD operations of the viewsets available for us.

5.2 URLS

We are almost done!๐Ÿš€๐Ÿš€๐Ÿš€ The next step is to connect the views to a url. So jump into the mysite/urls.py file and enter the following code

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('movies_api.urls')),
]

If you noticed, we are making reference to movies_api.urls a file we have not created yet. so let's do that. go into movies_api app and create a new urls.py file and key in the following command.

from django.urls import path, include
from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'movies', views.MovieViewSet)

# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browsable API.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

the routers module we imported from rest_framework handles the automatic configuration of URLs. Routers provide a simple, quick, and consistent way of wiring ViewSets logic to a set of URLs. Routers automatically map the incoming request to proper viewset action based on the request method type(i.e GET, POST, etc).

Now let's TeSt our API

start the django server by running the following command.

python manage.py runserver

go to localhost:8000

API ROOT.PNG Click on the movies endpoint to view a list of movie reviews

Movie list.PNG

That's it gang! ๐ŸŽ‰๐ŸŽ‰ Hope you had a fun and exciting time reading. See you in the next one. the code for this tutorial is available at https://github.com/itslogique/drf-article-code