DEV Community

Cover image for Django REST Framework: From Zero to Hero
Sanya_Lazy
Sanya_Lazy

Posted on

Django REST Framework: From Zero to Hero

Welcome to the world of API development with Django REST Framework! This tutorial is your comprehensive guide to building powerful and robust APIs using the most popular framework for Django.

Whether you're a complete beginner or have some experience with Django, this tutorial will take you from zero knowledge to confidently building your own APIs. We'll cover everything from the basics of REST principles to advanced concepts like authentication, authorization, and pagination.

Why Choose Django REST Framework?
Django REST Framework is a powerful and versatile tool that makes API development a breeze. Here's why it's the perfect choice:

  • Simplicity: Django REST Framework is designed to be easy to learn and use, even for beginners.
  • Flexibility: The framework is highly customizable, allowing you to tailor your APIs to your specific needs.
  • Robustness: Django REST Framework is built on top of Django, providing a solid foundation for building reliable and scalable APIs.
  • Large Community: You'll find a vibrant community of developers ready to help you with any questions or challenges you encounter.

Ready to Dive In?
Let's begin our journey to becoming API masters with Django REST Framework!

For Installation and Set up of Python and Django and also with python virtual environment use this reference link.

Let's Start

  • After creating Django project (you can check installation here), Install this package
pip install djangorestframework
Enter fullscreen mode Exit fullscreen mode
  • Add rest_framework to settings.py file.
INSTALLED_APPS = [
    ...,
    "rest_framework",
    "my_app" # app created
]
Enter fullscreen mode Exit fullscreen mode
  • Make sure to create my_app and add in settings.py file
  • Now make migrations and migrate
django manage.py makemigrations
django manage.py migrate
Enter fullscreen mode Exit fullscreen mode
  • In this we have around 5 steps:
  • Models
  • Serializers
  • Views
  • URL's
  • Adding in project URL's
  • Now if you want to use SQLite Database, then write code like this in my_app/models.py. If you can't find models.py file then create one in my_app/models.py.
from django.db import models

class User(models.Model):
    username = models.CharField(max_length=80, unique=True)
    password = models.CharField(max_length=150)

    def __str__(self):
        return self.username

# here this is basic model that stores user data.
Enter fullscreen mode Exit fullscreen mode
  • Now add serializers in my_app/serializers.py. If you can't find serializers.py file then create one in my_app/serializers.py.
from rest_framework import serializers
from .models import User # import required models

class RegistrationSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password']

    # example for password
    # password = serializers.CharField(write_only=True)

class LoginSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password']  # Define the fields for login

    username = serializers.CharField()
    password = serializers.CharField(write_only=True)

# This is basic code for user data
Enter fullscreen mode Exit fullscreen mode
  • Now add views in my_app/views.py. If you can't find views.py file then create one in my_app/views.py.
  • Here I have written code for two views as RegisterView and LoginView.
# code for RegisterView
class RegisterView(APIView):
    def post(self, request):
        serializer = RegistrationSerializer(data=request.data)
        if serializer.is_valid():
            # Access the validated data from the serializer
            username = six.b(serializer.validated_data['username']) 
            password = six.b(serializer.validated_data['password'])  

            user = User(username=username, password=password)
            user.save()

            return Response({"message": "user registered successfully"}, status=status.HTTP_201_CREATED)

Enter fullscreen mode Exit fullscreen mode
# code for LoginView
class LoginView(APIView):
    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            username = six.b(serializer.validated_data['username']) 
            password = six.b(serializer.validated_data['password'])  

            try:
                user = User.objects.get(username=username)  
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)

            return Response({"username": username})

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Enter fullscreen mode Exit fullscreen mode
  • the complete code for views.py
from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

from .models import User  #import models
from .serializers import RegistrationSerializer, LoginSerializer  #import serializers

# impot any packages
import six # Python 2 and 3 compatibility library package

class RegisterView(APIView):
    def post(self, request):
        serializer = RegistrationSerializer(data=request.data)
        if serializer.is_valid():
            # Access the validated data from the serializer
            username = six.b(serializer.validated_data['username']) 
            password = six.b(serializer.validated_data['password'])  

            user = User(username=username, password=password)
            user.save()

            return Response({"message": "user registered successfully"}, status=status.HTTP_201_CREATED)

class LoginView(APIView):
    def post(self, request):
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            username = six.b(serializer.validated_data['username']) 
            password = six.b(serializer.validated_data['password'])  

            try:
                user = User.objects.get(username=username)  
            except User.DoesNotExist:
                return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)

            return Response({"username": username})

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Enter fullscreen mode Exit fullscreen mode
  • Now add URL's in my_app/urls.py. If you can't find urls.py file then create one in my_app/urls.py.
from django.urls import path
from .views import RegisterView, LoginView

urlpatterns = [
    path('register/', RegisterView.as_view(), name='register'),
    path('login/', LoginView.as_view(), name='login'),
]
Enter fullscreen mode Exit fullscreen mode
  • Now add URL's in my_project/urls.py. Once check it is located in my_project. If you can't find urls.py file then create one in my_project/urls.py.
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    ...,
    path('auth/', include('my_app.urls'))
]
Enter fullscreen mode Exit fullscreen mode
  • Now the code is completed. Run makemigrations and migrate
python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode
  • Run the development server
python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Testing:

  • To use this API's, the URL's are like this
/auth/register/
- the complete URL `http://localhost:3000/auth/register/
- takes username, password
- stores in database

/auth/login/
- the complete URL `http://localhost:3000/auth/login/
- takes username, password
- returns values
Enter fullscreen mode Exit fullscreen mode
  • For testing you can use any API development platform like postman etc.

use headers

register api

login api

You have 5 steps

  1. Models
  2. Serializers
  3. Views
  4. URL's
  5. Adding in project URL's

*Reference: *
GitHub - LinkπŸ”—

Happy Coding 😴 - Be Lazy

Contact DM - Twitter(X)
Contact Mail - sanya.san@myyahoo.com

Top comments (2)

Collapse
 
david_polycarp profile image
David Polycarp

There are several important issues in your current implementation that I should point out.

Security Issues:

  1. You're storing passwords in plain text, which is a severe security vulnerability
  2. No password hashing is implemented
  3. No authentication tokens or session management
  4. The six.b() usage for username/password is unnecessary and potentially problematic

Logical Issues:

  1. Your LoginView is actually creating a new user instead of authenticating
  2. No actual login functionality is implemented
  3. Duplicate code between LoginView and RegisterView
Collapse
 
sanya_lazy profile image
Sanya_Lazy

It's just code of using 'REST Framework in django'. Not implementing fully functional production Login/Signup code.