Let’s create a ultimate blog app with Django Rest Framework and Reactjs!!
By: Mehul Singh Rathore
Tags: Rest Api, Django, API, Django Rest Framework, Web Development

In this post we are gonna create an API for a blogging website. So let’s jump into the code before wasting any time.

Setting up virtual environment:

python3 -m venv env

source env/bin/activate

Now let’s install our dependencies:

pip install django

pip install djangorestframework

Next step is to create a Django project and jump into it:

django-admin startproject tub #Tub is an acronym for "The Ultimate Blog"

cd tub

Alright let’s create a new blog app:

python manage.py startapp blog

Now its time plug our apps into our main project:

So first go to your tub/settings.py file and find the code block named INSTALLED_APPS and then

INSTALLED_APPS = [

...

'rest_framework',

'blog.apps.BlogConfig',

]

Since our setup is complete, its time to create a model to work with:

Now write this code in models.py file,

from django.db import models

from django.utils import timezone class Post(models.Model):

title = models.CharField(max_length=500)

description = models.TextField()

content = models.TextField()

date_posted = models.DateField(default=timezone.now)

category = models.CharField(max_length=100, default='web-dev')

Now let’s define our serializer class:

For those of you who don’t know what a serializer is, then I got you covered baby.

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON , XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

So let’s create a serializer.py file in our blog app directory, and we can grab our post model for our serializer

from rest_framework import serializers # Just import model in our serializer class

from blog.models import Post class PostSerializer(serializers.ModelSerializer):

class Meta:

model = Post

fields = ['id', 'title', 'description', 'content']

If you are familiar with Django then its time to create views or route views for our API:

So now open your views.py file and code along, now I can’t explain everything so in a blog post so if you want please visit my youtube video here:

Watch for more details

from blog.models import Post

from blog.serializer import PostSerializer

from rest_framework.views import APIView

from rest_framework.response import Response

from rest_framework import status

from django.http import Http404 #Get all posts

class PostList(APIView):

def get(self, request):

posts = Post.objects.all()

serializer = PostSerializer(posts, many=True)

return Response(serializer.data) #Create new posts

class PostCreate(APIView): def post(self, request):

serializer = PostSerializer(data=request.data)

if serializer.is_valid():

serializer.save()

return Response(serializer.data, status=status.HTTP_201_CREATED)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #Get full post

class PostDetail(APIView):

def get_object(self, pk):

try:

return Post.objects.get(pk=pk)



except Post.DoesNotExist:

raise Http404 def get(self, request, pk):

post = self.get_object(pk)

serializer = PostSerializer(post)

return Response(serializer.data) #Edit or delete a post

class PostEdit(APIView): def put(self, request, pk):

post = self.get_object(pk)

serializer = PostSerializer(post, data=request.data)

if serializer.is_valid():

serializer.save()

return Response(serializer.data)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk):

post = self.get_object(pk)

post.delete()

return Response(status=status.HTTP_204_NO_CONTENT)

Now let’s create our URL routes:

Now first create a urls.py file in blog app directory, and then make your patterns,

from django.urls import path

from blog import views urlpatterns = [

path('blog/', views.PostList.as_view()),

path('blog/create/', views.PostCreate.as_view()),

path('blog/<int:pk>', views.PostDetail.as_view()),

path('blog/<int:pk>/edit/', views.PostEdit.as_view())

]

At last, let’s plug our URL routes into our main project:

In project’s urls.py file enter,

from django.contrib import admin

from django.urls import path, include urlpatterns = [

path('admin/', admin.site.urls),

path('', include('blog.urls'))

]

Our API is partially complete but it’s good for now. In another post we are gonna complete our API with token authentication but till that stay tuned.

And if you like to learn this in detail check out my video and Imma link it down below.