Django REST Framework Tutorial – Register Login Logout API

In this tutorial, you will learn how to create User Registration, Login and Logout Arrangement using Django Rest Framework. For this tutorial we volition use Django Residuum Knox Library for Token Based Hallmark Organization for Rest Framework. Knox provides piece of cake to use authentication for Django Residuum Framework. Knox hallmark is token based, similar to the TokenAuthentication built in to DRF.

Django Rest Framework Login Logout Authentication

Django Remainder Framework Projection Setup

We will install following libraries for django, django rest framework and django rest knox.

pip install djangorestframework pip install django-rest-knox

Later installing the to a higher place library. Addrest_framework andknox to yourINSTALLED_APPS, removerest_framework.authtoken if yous were using it.

INSTALLED_APPS = [     ...'rest_framework',     'knox',                ]

Brand knox's TokenAuthentication your default authentification form for django-remainder-framework, in settings.py file:

REST_FRAMEWORK = {     'DEFAULT_AUTHENTICATION_CLASSES': [         # 'rest_framework.hallmark.BasicAuthentication',         # 'rest_framework.hallmark.SessionAuthentication',         'knox.auth.TokenAuthentication',     ] }

Note – The to a higher place REST_FRAMEWORK allows both session based and token based authentication.

User Registration API using Django Rest Framework

At present we volition User Registration API Using Django Residue Framework. We volition create Register Serializer for User Register API.

Create a file in your app named serializers.py and add together the blare code –

from rest_framework import serializers from django.contrib.auth.models import User  # User Serializer grade UserSerializer(serializers.ModelSerializer):     class Meta:         model = User         fields = ('id', 'username', 'e-mail')  # Register Serializer form RegisterSerializer(serializers.ModelSerializer):     class Meta:         model = User         fields = ('id', 'username', 'email', 'password')         extra_kwargs = {'password': {'write_only': Truthful}}      def create(self, validated_data):         user = User.objects.create_user(validated_data['username'], validated_data['e-mail'], validated_data['password'])          return user

After creating serializer, we need to create DRF APIView.

In views.py file, add together the post-obit lawmaking –

from rest_framework import generics, permissions from rest_framework.response import Response from knox.models import AuthToken from .serializers import UserSerializer, RegisterSerializer  # Register API form RegisterAPI(generics.GenericAPIView):     serializer_class = RegisterSerializer      def post(self, request, *args, **kwargs):         serializer = self.get_serializer(data=request.data)         serializer.is_valid(raise_exception=Truthful)         user = serializer.save()         render Response({         "user": UserSerializer(user, context=self.get_serializer_context()).data,         "token": AuthToken.objects.create(user)[ane]         })

In urls.py file add following path –

from .views import RegisterAPI from django.urls import path  urlpatterns = [     path('api/register/', RegisterAPI.as_view(), proper name='register'), ]

That's it. At present go to url ( http://localhost:8000/api/register/ ) in your browser or mail and the following in content.

{     "username": "admin",     "email": "[email protected]",     "password": "[email protected]" }

And in response, you will get similar data –

{     "user": {         "id": 2,         "username": "admin1",         "electronic mail": "[email protected]"     },     "token": "790e890d571753148bbc9c4447f106e74ecf4d1404f080245f3e259703d58b09" }

Login Logout API Hallmark using Django Residual Framework

Knox provides ane class to handle hallmark. Nosotros will apply KnoxLoginView to create login logout arrangement.

We take already create a app with name accounts. Inside this app we will create our LoginView.

In accounts/views.py file, add following code –

from django.contrib.auth import login  from rest_framework import permissions from rest_framework.authtoken.serializers import AuthTokenSerializer from knox.views import LoginView every bit KnoxLoginView  class LoginAPI(KnoxLoginView):     permission_classes = (permissions.AllowAny,)      def postal service(self, request, format=None):         serializer = AuthTokenSerializer(data=request.data)         serializer.is_valid(raise_exception=True)         user = serializer.validated_data['user']         login(request, user)         render super(LoginAPI, self).mail service(request, format=None)

Note login(asking, user) line in above code, will as well create session based authentication with token based authentication.

And in accounts/urls.py file

from knox import views as knox_views from .views import LoginAPI from django.urls import path  urlpatterns = [     path('api/login/', LoginAPI.as_view(), name='login'),     path('api/logout/', knox_views.LogoutView.as_view(), proper name='logout'),     path('api/logoutall/', knox_views.LogoutAllView.as_view(), name='logoutall'), ]

That's it. Now go to url ( http://localhost:8000/api/login/ ) in your browser or post and the post-obit in content.

{     "username": "admin",     "countersign": "[email protected]" }

It volition return in response like this –

{     "decease": "2020-06-29T02:56:44.924698Z",     "token": "99a27b2ebe718a2f0db6224e55b622a59ccdae9cf66861c60979a25ffb4f133e" }

In this tutorial you learnt to create authentication system similar user registration, login and logout organization using Django Rest Framework. This tutorial explain Session Based Hallmark and Token Based Authentication in the Django Residue Framework.

Observe this tutorial on GitHub – https://github.com/studygyaan/django-balance-framework-tutorial