Home » Django & REST Api » Developing first REST API using Django Rest Framework ( DRF )

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,

(env)$ tree helloproject/
helloproject/
├── asgi.py
├── __init__.py
├── settings.py
├── urls.py
└── wsgi.py
$ cd helloproject 
$ django-admin startapp helloapp
$ tree helloapp/
helloapp/
├── admin.py
├── apps.py
├── __init__.py
├── migrations
│ └── __init__.py
├── models.py
├── tests.py
└── views.py

1 directory, 7 files
$ cd ..

Now sync your database for the first time,

$ python manage.py migrate
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
$ tree helloproject/
helloproject/
├── asgi.py
├── helloapp
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── settings.cpython-36.pyc
│ └── urls.cpython-36.pyc
├── settings.py
├── urls.py
└── wsgi.py

3 directories, 15 files

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

$ python manage.py 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 http://127.0.0.1:8000/
Quit the server with CONTROL-C.

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.

django

We will write the model in our helloapp as below,

$ vim helloproject/helloapp/models.py
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

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 models.py, we need to write the “serializers” which is an addition to developing REST API using Django REST Framework..

$ vim helloproject/helloapp/serializers.py
from rest_framework import serializers
from helloproject.helloapp.models import UserInfo

class UserInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserInfo
        fields = ('username', 'email', 'age')

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/views.py
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.

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

$ vim helloproject/helloapp/urls.py
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)),
]

With writing “models.py” , “serializers.py” , “views.py” and “urls.py” 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” urls.py as,

$ vim helloproject/urls.py
from django.contrib import admin
from django.urls import include, path

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

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

INSTALLED_APPS = [
    'rest_framework',
    'helloproject.helloapp'
]

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

$ python manage.py makemigrations
$ python manage.py migrate 

We can start the server as,

$ python manage.py 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 http://127.0.0.1:8000/
Quit the server with CONTROL-C.

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 http://127.0.0.1:8000 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”


Subscribe our Rurban Life YouTube Channel.. "Rural Life, Urban LifeStyle"

1 thought on “Developing first REST API using Django Rest Framework ( DRF )”

Leave a Comment