Django REST framework (DRF) is a powerful and flexible toolkit for building web APIs. In this tutorial, we’ll learn how to build a CRUD API in just 15 minutes using the Django REST framework.

To build our sample to-do list application, we’ll start by setting up the Django REST framework in a Django project, followed by a complete tutorial on how to create a CRUD REST API with the Django REST framework.

Use my previous article to know about Get Method

Use Previous project or Create a Django project drinks with the following command

django-admin startproject drinks

Then, cd into the new drinks folder and create a new app for your API

python manage.py startapp core

Run your initial migrations of the built-in user model:

python manage.py migrate

Next, add rest_framework and drinks to the INSTALLED_APPS inside the settings.py file:

# settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'core'
]

Create a model in models.py file like

from django.db import models

# Create your models here.


class Drink(models.Model):
  name=models.CharField(max_length=200)
  description = models.CharField(max_length=500)


  def __str__(self):
    return self.name+" "+self.description

Then apply Commands and Create a SuperUser to Our project:

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser

Model serializer

To convert the Model object to an API-appropriate format like JSON, Django REST framework uses the ModelSerializer class to convert any model to serialized JSON objects:

from rest_framework import serializers
from .models import Drink

class DrinkSerializer(serializers.ModelSerializer):
  class Meta:
    model= Drink
    fields = '__all__'

Creating API views in Django -Post Method

In this section, we’ll walk through how to create two API views, list view and we cannot specify the Detailed as it is not a primary key class or method

The first API view class deals with the core/api/ endpoint, in which it handles GET for listing all to-dos of a given requested user and POST for creating a new to-do. Notice that we’ve added permission_classes, which allows authenticated users only:

Post Method

Before going to POST we have to display the previous Objects by using Get method

POST request is used to send data to the server enclosed in the request body.It is meant to use when you’d like to create new entities.. Let’s head to our views and create a POST request handler for our Drink model.

Let’s head to drinks/views.py, create a new class with a post() method that will receive a POST request body, validate it and create an object of class Drink in our DB:

from .models import Drink
from .serializers import DrinkSerializer
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status


class drink_list(APIView):
    def get(self, request, format=None):
        drinks = Drink.objects.all()
        serializer = DrinkSerializer(drinks, many=True)
        return Response(serializer.data)

    def post(self, request, format=None):
        serializer = DrinkSerializer(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)

Here you can observe that first, we created a serializer object from the request.data using the DrinkSerializer we’ve created previously. The is_valid() function returns a Boolean value that indicates whether the request body can be used to create a Drink object. And the save() method will create a new instance of Drink.

The Response must be initialized with the data to be returned. This data can be an instance of any type of Python object like boolstrdict etc.

Other optional parameters include the status that sets the HTTP response code, content-type that indicates how the data will be rendered, template_name that can be used if HTMLRenderer is selected and headers if we explicitly want to send certain headers in the HTTP response.

Let’s set up and expose an endpoint to use our post() method. We do this by editing the drinks/urls.py and including our app’s exposed endpoints:

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('core.urls')),
]

With the endpoint exposed, we’ll want to register the actual drink_list class as a view for the user. Note that this doesn’t include a view in the sense of a GUI – it’s the request handler.

We’ve included the core.urls here, and delegated the logic that connects the view to the urls.py script within core. In the core folder, create a new file called urls.py, and link the drinks/ locator with the drink_list class:

from django.urls import path,include
from . import views

urlpatterns = [
     path('',views.drink_list.as_view()),
]

Running the Server

Let’s run the app :

$ python3 manage.py runserver

This will start the local server at http://127.0.0.1:8000

You Can get Output as

By Using json Format providing an item/drink On Clicking POST Button

We can get the Output as

Conclusion

Congratulations! You’ve successfully built your first fully functional CRUD Django REST API.

It is Difficult to Building a RESTful API  ,but Django REST framework handles complexity very well. I hope you have fun building new APIs using the Django REST framework, and be sure to leave a comment if you have any questions. Happy coding!