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
- Add rest_framework to
settings.py
file.
INSTALLED_APPS = [
...,
"rest_framework",
"my_app" # app created
]
- 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
- 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 findmodels.py
file then create one inmy_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.
- Now add
serializers
inmy_app/serializers.py
. If you can't findserializers.py
file then create one inmy_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
- Now add
views
inmy_app/views.py
. If you can't findviews.py
file then create one inmy_app/views.py
. - Here I have written code for two views as
RegisterView
andLoginView
.
# 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)
# 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)
- 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)
- Now add
URL's
inmy_app/urls.py
. If you can't findurls.py
file then create one inmy_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'),
]
- Now add
URL's
inmy_project/urls.py
. Once check it is located inmy_project
. If you can't findurls.py
file then create one inmy_project/urls.py
.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
...,
path('auth/', include('my_app.urls'))
]
- Now the code is completed. Run makemigrations and migrate
python manage.py makemigrations
python manage.py migrate
- Run the development server
python manage.py runserver
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
- For testing you can use any API development platform like postman etc.
You have 5 steps
- Models
- Serializers
- Views
- URL's
- Adding in project URL's
*Reference: *
GitHub - Linkπ
Happy Coding π΄ - Be Lazy
Contact DM - Twitter(X)
Contact Mail - sanya.san@myyahoo.com
Top comments (0)