How to Create Authentication APIs (Login & Register API) in Django with Django Rest Framework
Django Rest Framework (DRF) is a powerful and flexible toolkit for building Web APIs in Django applications. When developing modern web applications, implementing secure authentication is a crucial aspect. In this article, we will walk through the process of creating a simple Authentication API in Django using Django Rest Framework, covering both login and registration functionalities.
Prerequisites
Before we begin, make sure you have the following installed:
1. Python and Django: Install the latest version of Python and Django on your system. You can install Django using the following command:
pip install django
2. Django Rest Framework: Install Django Rest Framework using the following command:
pip install djangorestframework
Step 1: Create a Django Project and App
Start by creating a new Django project and a Django app within the project. Open a terminal and run the following commands:
django-admin startproject authentication_project cd authentication_project python manage.py startapp authentication_app
Step 2: Configure Django Settings
Add the newly created app and Django Rest Framework to the INSTALLED_APPS in the settings.py file:
# authentication_project/settings.py INSTALLED_APPS = [ # ... 'rest_framework', 'authentication_app', ]
Step 3: Create User Model
In the models.py file of the authentication_app, create a custom User model that extends the AbstractBaseUser and PermissionsMixin provided by Django:
# authentication_app/models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class CustomUserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] def __str__(self): return self.email
Step 4: Run Migrations
Run the initial migrations to create the database tables for the custom User model:
python manage.py makemigrations python manage.py migrate
Step 5: Create Serializer for User Model
In the serializers.py file of the authentication_app, create a serializer for the custom User model:
# authentication_app/serializers.py from rest_framework import serializers from .models import CustomUser class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ('id', 'email', 'first_name', 'last_name', 'is_active', 'is_staff')
Step 6: Create Views for Registration and Login
In the views.py file of the authentication_app, create views for user registration and login:
# authentication_app/views.py from rest_framework import generics, permissions from rest_framework.response import Response from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from .models import CustomUser from .serializers import CustomUserSerializer class RegisterUserView(generics.CreateAPIView): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer permission_classes = (permissions.AllowAny,) class CustomObtainAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): response = super().post(request, *args, **kwargs) token = Token.objects.get(key=response.data['token']) user = CustomUser.objects.get(id=token.user_id) serializer = CustomUserSerializer(user) return Response({'token': token.key, 'user': serializer.data})
Step 7: Configure URLs
In the urls.py file of the authentication_app, define the URLs for registration and login views:
# authentication_app/urls.py from django.urls import path from .views import RegisterUserView, CustomObtainAuthToken urlpatterns = [ path('register/', RegisterUserView.as_view(), name='register'), path('login/', CustomObtainAuthToken.as_view(), name='login'), ]
Include these URLs in the main urls.py file of your project:
# authentication_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('authentication_app.urls')), ]
Step 8: Run the Development Server
Start the development server by running the following command:
python manage.py runserver
Visit http://localhost:8000/admin to access the Django admin panel and create a new user. Then, use the provided API endpoints for registration and login:
- Registration:
POST http://localhost:8000/api/register/ - Login:
POST http://localhost:8000/api/login/
These endpoints will return a token that you can use for subsequent authenticated requests.