0% found this document useful (0 votes)
4 views10 pages

3 - Django REST API Blog Project

The document outlines the architecture and implementation steps for a Blog API System using Django REST Framework (DRF) with JWT authentication. It details the end-to-end flow from frontend requests to backend processing, including model creation, serializers, permissions, and viewsets. Additionally, it provides instructions for setting up URLs, JWT configuration, and testing the API using Postman.

Uploaded by

callhimzmy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

3 - Django REST API Blog Project

The document outlines the architecture and implementation steps for a Blog API System using Django REST Framework (DRF) with JWT authentication. It details the end-to-end flow from frontend requests to backend processing, including model creation, serializers, permissions, and viewsets. Additionally, it provides instructions for setting up URLs, JWT configuration, and testing the API using Postman.

Uploaded by

callhimzmy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DRF Working Diagram (End-to-End Flow)

Step-by-step flow:
1. Frontend sends request (Axios / Fetch)
2. API receives request (View / ViewSet)
3. Serializer converts data
4. Model interacts with database
5. Data comes back → converted to JSON
6. Frontend displays it
Blog Project Structure
Blog API System (DRF + JWT + Frontend)

Blog API System


Backend (Django DRF)
User login (JWT)
CRUD for posts
Permissions (only author can edit)

Frontend (Bootstrap HTML + JS)


Display posts
Create new post
Login system
Protected routes
Project Creation Step by Step

Install the required packages

pip install django


pip install djangorestframework
pip install djangorestframework-simplejwt

Create Project & App

django-admin startproject blog_project


django-admin startproject blog_app

Add Apps in [Link]

INSTALLED_APPS = [
'rest_framework',
'blog_app',
]
Create Model (Post) – [Link]

from [Link] import models


from [Link] import User

class Post([Link]):
title = [Link](max_length=200)
content = [Link]()

# Link post with user (author)


author = [Link](User, on_delete=[Link])

created_at = [Link](auto_now_add=True)

def __str__(self):
return [Link]

Run Migrations

python [Link] makemigrations


python [Link] migrate

Register model in Admin - [Link]

from [Link] import admin


from .models import Post

[Link](Post)
Create Serializer - [Link]

from rest_framework import serializers


from .models import Post

class PostSerializer([Link]):

# Show username instead of ID


author = [Link](source='[Link]')

class Meta:
model = Post
fields = '__all__'

Create Permission (Author Only) - [Link]

from rest_framework.permissions import BasePermission

class IsAuthorOrReadOnly(BasePermission):

def has_object_permission(self, request, view, obj):

# Allow read-only methods for everyone


if [Link] in ['GET', 'HEAD', 'OPTIONS']:
return True

# Only author can edit/delete


return [Link] == [Link]
Create ViewSet - [Link]

from rest_framework.viewsets import ModelViewSet


from .models import Post
from .serializers import PostSerializer
from rest_framework.permissions import IsAuthenticated
from .permissions import IsAuthorOrReadOnly

class PostViewSet(ModelViewSet):

queryset = [Link]()
serializer_class = PostSerializer

# Only logged-in users can access API


permission_classes = [IsAuthenticated, IsAuthorOrReadOnly]

def perform_create(self, serializer):


# Automatically assign logged-in user as author
[Link](author=[Link])
Setup URLs Project - [Link]

from [Link] import admin


from [Link] import path, include

# JWT Views
from rest_framework_simplejwt.views import TokenObtainPairView,
TokenRefreshView

urlpatterns = [
path('admin/', [Link]),

# API routes
path('api/', include('blog_app.urls')),

# JWT Authentication routes


path('api/token/', TokenObtainPairView.as_view()),
path('api/token/refresh/', TokenRefreshView.as_view()),
]

Setup URLs (Router) - blog_app/[Link]

from rest_framework.routers import DefaultRouter


from .views import PostViewSet

router = DefaultRouter()
[Link]('posts', PostViewSet)

urlpatterns = [Link]
JWT Configuration - [Link]

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.[Link]',
)
}

POSTMAN Testing

Get JWT Token (LOGIN)

POST: [Link]

raw → JSON

{
"username": "admin",
"password": "admin"
}

Response

{
"refresh": "xxxxx",
"access": "abc123xyz"
}

Set Authorization - Go to → Headers


Key: Authorization
Value: Bearer YOUR_ACCESS_TOKEN
Create Post:
POST: [Link]

raw → JSON
{
"title": "My First Blog",
"content": "This is my content"
}

GET ALL POSTS:

GET [Link]

GET SINGLE POST

GET [Link]

UPDATE POST

PUT [Link]

DELETE POST

DELETE [Link]

You might also like