Django is one of the popular Web development frameworks. It is easy to learn. You can learn Django with a beginner-level language of Python. You can create a full-fledged dynamic website within 4-5 hours in Django.
Django takes care of various features like Handling the server, Database, etc. It also provides default database dbsqlite3 when creating the project. So, If you are looking for a web development framework that is easy to learn, You should consider Django once.
Django is basically built for Web development. But, If you have a third-party frontend framework in mind and want to use Django as an API, You can create a REST API using Django rest framework module. I've recently talked about How you can create CRUD API using the Django rest framework, You can check out here.
Today, we will be learning about a new topic in the Django rest framework that is Token Authentication. Well, Token authentication is useful when you want to create login functionality in your web or app.
With token authentication, You can generate tokens for each user, and with that token, the user can get his details without logging in every time.
How to Create Register and Login API using Django Rest framework and Token Authentication?
1 . First of all, make sure you have already created your Django Project and Installed Django Rest Framework.
2. Make sure to add "rest_framework" inside settings.py installed Apps section.
3. Next, Create a new app named "api" inside your django project.
4. Create Urls.py file inside the app and include it in the main project urls.
5. Next, create serializers.py file inside your app "api".
6. Copy and Paste the below code
from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework.response import Response
from rest_framework import status
from rest_framework.validators import UniqueValidator
from django.contrib.auth.password_validation import validate_password
#Serializer to Get User Details using Django Token Authentication
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "first_name", "last_name", "username"]
#Serializer to Register User
class RegisterSerializer(serializers.ModelSerializer):
email = serializers.EmailField(
required=True,
validators=[UniqueValidator(queryset=User.objects.all())]
)
password = serializers.CharField(
write_only=True, required=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = ('username', 'password', 'password2',
'email', 'first_name', 'last_name')
extra_kwargs = {
'first_name': {'required': True},
'last_name': {'required': True}
}
def validate(self, attrs):
if attrs['password'] != attrs['password2']:
raise serializers.ValidationError(
{"password": "Password fields didn't match."})
return attrs
def create(self, validated_data):
user = User.objects.create(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name']
)
user.set_password(validated_data['password'])
user.save()
return user
In the above code, we have defined two classes. First class is to get use details when passing the token and the second class is to create/register a new user in the database.
8. Next, Open api/views.py file and paste the following code.
from rest_framework.permissions import AllowAny
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import UserSerializer,RegisterSerializer
from django.contrib.auth.models import User
from rest_framework.authentication import TokenAuthentication
from rest_framework import generics
# Class based view to Get User Details using Token Authentication
class UserDetailAPI(APIView):
authentication_classes = (TokenAuthentication,)
permission_classes = (AllowAny,)
def get(self,request,*args,**kwargs):
user = User.objects.get(id=request.user.id)
serializer = UserSerializer(user)
return Response(serializer.data)
#Class based view to register user
class RegisterUserAPIView(generics.CreateAPIView):
permission_classes = (AllowAny,)
serializer_class = RegisterSerializer
In the above code, we have used two class-based views. The first view is for getting the user details and the second one is to register the user in the database.
9. Next, In api/urls.py file. copy and paste the below code.
from django.urls import path
from .views import UserDetailAPI,RegisterUserAPIView
urlpatterns = [
path("get-details",UserDetailAPI.as_view()),
path('register',RegisterUserAPIView.as_view()),
]
10. Atlast, Open your project root urls.py file and paste the below code.
from django.contrib import admin
from django.urls import path,include
from rest_framework.authtoken import views
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('api.urls')),
path('api-token-auth', views.obtain_auth_token)
]
11. Your Register and Login API has been created.
12. You can test your API using Postman or any other platform.
Note: Make sure to send Token in "get-details/" url in Headers as follows
key: Authorization
value: TOKEN <token>
Comments