Developing first REST API using Django Rest Framework ( DRF )

This post is in continuation with our previous post “Installing Django and Django-REST Framework on Ubuntu for developing REST API’s” which setup the development environment required to start developing rest API.

$ python3 -m venv env 

The final step in setting up your virtual environment is to activate it:

$ source env/bin/activate 

Now, we need to install “django” and “django rest framework” using below command,

(env)$ pip install django 
(env)$ pip install djangorestframework 

Now, we are ready to start the project,

(env)$ django-admin startproject helloproject . 

Notice: the dot ( . ) at the end of command.

Once you run above command, you will see following new files getting created,

[bash] (env)$ tree helloproject/ helloproject/ ├── ├── ├── ├── └── [/bash]
$ cd helloproject 
$ django-admin startapp helloapp 
[bash] $ tree helloapp/ helloapp/ ├── ├── ├── ├── migrations │   └── ├── ├── └── 1 directory, 7 files [/bash]
$ cd .. 

Now sync your database for the first time,

$ python migrate 
[bash] Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial… OK Applying auth.0001_initial… OK Applying admin.0001_initial… OK Applying admin.0002_logentry_remove_auto_add… OK Applying admin.0003_logentry_add_action_flag_choices… OK Applying contenttypes.0002_remove_content_type_name… OK Applying auth.0002_alter_permission_name_max_length… OK Applying auth.0003_alter_user_email_max_length… OK Applying auth.0004_alter_user_username_opts… OK Applying auth.0005_alter_user_last_login_null… OK Applying auth.0006_require_contenttypes_0002… OK Applying auth.0007_alter_validators_add_error_messages… OK Applying auth.0008_alter_user_username_max_length… OK Applying auth.0009_alter_user_last_name_max_length… OK Applying auth.0010_alter_group_name_max_length… OK Applying auth.0011_update_proxy_permissions… OK Applying sessions.0001_initial… OK [/bash] [bash] $ tree helloproject/ helloproject/ ├── ├── helloapp │   ├── │   ├── │   ├── │   ├── migrations │   │   └── │   ├── │   ├── │   └── ├── ├── __pycache__ │   ├── __init__.cpython-36.pyc │   ├── settings.cpython-36.pyc │   └── urls.cpython-36.pyc ├── ├── └── 3 directories, 15 files [/bash]

Now, if we start the server as below, we will see the default web page of the django server..

[bash] $ python runserver Watching for file changes with StatReloader Performing system checks… System check identified no issues (0 silenced). August 14, 2020 – 13:30:21 Django version 3.1, using settings ‘helloproject.settings’ Starting development server at Quit the server with CONTROL-C. [/bash]

The default web page shown by Django server is as below,

django project

With this we are ready to start the development of our very first REST API. As we seen in our another post “Understanding Django project and app binding / architecture” to start development with Django, we need to start with developing model’s , we will just add the same image below for better understanding of architecture.


We will write the model in our helloapp as below,

$ vim helloproject/helloapp/ 
[bash] from django.db import models # Create your models here. class UserInfo (models.Model) : username = models.CharField(max_length=100) email = models.CharField(max_length=100) age = models.IntegerField() def __str__(self) : return self.username [/bash]

This model, has 3 fields “username” , “email” and “age” as an User Information for which we are trying to write an API.

Next to writing, we need to write the “serializers” which is an addition to developing REST API using Django REST Framework..

$ vim helloproject/helloapp/ 
[bash] from rest_framework import serializers from helloproject.helloapp.models import UserInfo class UserInfoSerializer(serializers.ModelSerializer): class Meta: model = UserInfo fields = (‘username’, ’email’, ‘age’) [/bash]

The serializers does the reading of database fields from model and enables the serialization of the model fields.

The next to write the REST API is we combine “serializers” and “models” to write our views as below,

$ vim helloproject/helloapp/ 
[bash] from django.shortcuts import render from rest_framework import viewsets from helloproject.helloapp.models import UserInfo from helloproject.helloapp.serializers import UserInfoSerializer class UserInfoView(viewsets.ModelViewSet) : queryset = UserInfo.objects.all() serializer_class = UserInfoSerializer # Create your views here. [/bash]

Now, this view needs to be mapped with url in the same app as below,

$ vim helloproject/helloapp/ 
[bash] from django.urls import include, path from rest_framework import routers from helloproject.helloapp import views router = routers.DefaultRouter() router.register(r’users’, views.UserInfoView) urlpatterns = [ path(”, include(router.urls)), ] [/bash]

With writing “” , “” , “” and “” in sequence we are ready with our first REST API in Django REST App “helloapp”

Now, this “helloapp” url needs to be mapped with the “helloproject” as,

$ vim helloproject/ 
[bash] from django.contrib import admin from django.urls import include, path urlpatterns = [ path(‘admin/’,, path(”, include(‘helloproject.helloapp.urls’)), ] [/bash]

The last step to get minimum API working now is to modify projects to appened INSTALLED_APPS with your django app details,

[bash] INSTALLED_APPS = [ ‘rest_framework’, ‘helloproject.helloapp’ ] [/bash]

Since working with developing API, we modified to add UserInfo model, hence we need to run below command to make sure the database is synced with modifications,

$ python makemigrations 
$ python migrate 

We can start the server as,

[bash] $ python runserver Watching for file changes with StatReloader Performing system checks… System check identified no issues (0 silenced). August 14, 2020 – 17:08:48 Django version 3.1, using settings ‘helloproject.settings’ Starting development server at Quit the server with CONTROL-C. [/bash]

Now, if we visited this server URL in browser, we can see the API root web page with the details of REST API we developed as,

Notice Here : we just typed the url in browser and it shown the API Root without any login required.. which is serious security issue if we are developing the proprietary software hence its important that the data is protected with proper login mechanism.

Next post : “How to set password authentication for Api Root / DefaultRouter in Django REST”

Leave a Comment