To create a Django API endpoint for registering a user and generating a JSON Web Token (JWT) using function-based views, you can follow these steps:
Install the required packages:
pip install django djangorestframework djangorestframework-simplejwt
django-admin startproject myproject
cd myproject
python manage.py startapp myapp
Configure Django settings in settings.py
:
INSTALLED_APPS = [
...
'rest_framework',
'myapp',
]
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework_simplejwt.authentication.JWTAuthentication',
],
}
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
}
Define the user registration and authentication endpoints in myapp/views.py
:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.models import User
from rest_framework_simplejwt.tokens import RefreshToken
@api_view(['POST'])
def register_user(request):
username = request.data.get('username')
password = request.data.get('password')
if not username or not password:
return Response({'error': 'Please provide both username and password.'}, status=status.HTTP_400_BAD_REQUEST)
try:
user = User.objects.create_user(username=username, password=password)
refresh = RefreshToken.for_user(user)
return Response({'token': str(refresh.access_token)}, status=status.HTTP_201_CREATED)
except:
return Response({'error': 'Unable to register the user.'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
@api_view(['POST'])
def authenticate_user(request):
username = request.data.get('username')
password = request.data.get('password')
if not username or not password:
return Response({'error': 'Please provide both username and password.'}, status=status.HTTP_400_BAD_REQUEST)
try:
user = User.objects.get(username=username)
if user.check_password(password):
refresh = RefreshToken.for_user(user)
return Response({'token': str(refresh.access_token)}, status=status.HTTP_200_OK)
else:
return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED)
except User.DoesNotExist:
return Response({'error': 'Invalid credentials.'}, status=status.HTTP_401_UNAUTHORIZED)
5. Define the API endpoints in myapp/urls.py
:
from django.urls import path
from myapp import views
urlpatterns = [
path('register/', views.register_user, name='register_user'),
path('authenticate/', views.authenticate_user, name='authenticate_user'),
]
6. Include the app URLs in the project urls.py
:
from django.urls import path, include
urlpatterns = [
...
path('api/', include('myapp.urls')),
]
python manage.py runserver
Now you should be able to send POST requests to the following endpoints:
To register a user: http://localhost:8000/api/register/
{"username": "myusername", "password": "mypassword"}
{"token": "your-jwt-token"}
To authenticate a user: http://localhost:8000/api/authenticate/
{"username": "myusername", "password": "mypassword"}
{"token": "your-jwt-token"}
Remember to replace localhost:8000
with the appropriate URL if you are running the server on a different host or port.
Copyright By@TimPat - 2024
BACK TO TOP