Django REST Framework : JWT, Custom User, Protecting resources.
This is part-1 of the DRF/Django Tutorial series.
Recently I had the opportunity to create a Consulting Application using DRF (Django Rest Framework) for Backend API Development tool , MySQL Database, NextJS for front UI and Bootstrap for responsive design.
This is part-1 of this series where I will be explaining :
Creating a Custom User Model for mobile based authentication
Using JWT for authentication
Protecting web paths with JWT Authentication
What is DRF ?
DRF is a toolkit for Django used mainly for building JSON based REST Web APIs.
What is Django?
Django is a python-based web framework based model–template–views (MTV) architectural pattern used to create scalable secure web applications.
What is MTV ?
It is a design architecture followed by Django to create web applications. It has four main parts:
URL Manager : Maps request to a View
View: is the request processor. Handles requests and generates responses.
Template: Presentation layer, decides how response is displayed.
Model: Data access layer, generally mapped to database table.
Installation
Install python, Django, django-rest-framework , mysqlclient and djangorestframework_simplejwt as follows
pip3 install django
pip install djangorestframework
pip3 install mysqlclient
pip3 install djangorestframework_simplejwt
Now create a MYSQL database named “movie_db”.
Lets create a Django project named “notice_app” and an App “notices” inside “notice_app” project
django-admin startproject notice_app
cd notice_app
python3 manage.py startapp notices
So what is a project and what is an app ?
A project refers to the entire application and all its parts. An app refers to a submodule of the project. A Project typically contains one or more apps, each addressing a separate concern.
Update Settings
Now open notice_app/settings.py and add “rest_framework” and “notices” to installed apps. “rest_framework” represents DRF and “notices” is the app we have created above.
Update database settings for MYSQL (again in notice_app/settings.py) as follows:
To enable JWT Authentication, add the following at last in notice_app/settings.py
Customizing user model
A model is a python class containing essential fields and behaviour of the data you’re storing. Generally, each model maps to a single database table. A Model is created by subclassing django.db.models.Model class. Django provides built in authentication system. By default class django.contrib.auth.models.User uses “username” to identify users. We want to authenticate user using mobile number, so we have to override default mechanism. Let us do so by creating a class by subclassing AbstractBaseUser class provided by Django as follows :
Notice that:
We have created a class CustomUser by subclassing AbstractBaseUser class and a mixin PermissionsMixin. Mixins in python are used to inject some code to a class without causing multiple inheritnace issues. PermissionsMixin is used to manage user permissions.
Also notice that we have used USERNAME_FIELD = “mobile”. In other words mobile field is now used to identify User instead of username.
There is one more line (Line# 18) that needs little explaination:
objects = CustomUserManager()
We have to create a class CustomUserManager by extending BaseUserManager class provided by Django. This defines how users and superuser shall be created, keeping mobile field as username in mind.
Migrations
Migration refers to the management of changes to relational database schemas. It allows us to create, alter, drop database tables and objects using Django ecosystem. So if you want to create a table create a model, make migration and migarte it. Simple. Let’s see it in action
Create a model for “Notice”
Now execute inside notice_app folder
python3 manage.py makemigrations notices
python3 manage.py migrate
This will create database tables for “CustomUser” and “Notice” models.
Serializers
Serializers are used to transform Django objects into data formats that front-end frameworks and javascript can understand and vide-versa. Thus if we want to create Model objects using Json or generate Json for Django Model objects, we need serializers.
Let’s create serializer for Notice model, containing all fields
Creating fixtures
A fixture is a collection of files that contain the serialized contents of the database.
It’s sometimes useful to prepopulate your database with hard-coded data when you’re first setting up an app. You can provide initial data with migrations or fixtures.
Create a folder named “notices/fixtures” and create a file named “notices/fixtures/notices.json”
Now executing command below will populate database table with two records.
python3 manage.py loaddata notices
Creating views
View for User Registration
JWT Restricted View for Listing all Notices (Refer to Line# 8)
Creating URLS for Views
First create URL PATTERNS for app “notices”
Now Map those urls to Project URLs
Thus we now have following end points:
POST http://127.0.0.1:8000/notices/register
You can see user-registraion, user-login and access to jwt-protected path in action here:
You may download source code from this github repository : https://github.com/mansha99/django-drf-jwt
Happy Coding.