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 the installation
Create a Django project called 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
rest_framework and drinks to the
INSTALLED_APPS inside the
# 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
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
In this section, we’ll walk through how to create two API views, list view and detail view.
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:
GET() method first fetches all the objects from the model by filtering with the requested user ID. Then, it serializes from the model object to a JSON serialized object. Next, it returns the response with serialized data and status as
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): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): drinks = Drink.objects.all() serializer = DrinkSerializer(drinks, many=True) return Response(serializer.data)
Now that we’ve successfully created our first endpoint view, let’s create the second endpoint
/<int:todo_id> API view.
In this API view class, we need to create three methods for handling the corresponding HTTP method,
GET as discussed above:
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): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): drinks = Drink.objects.all() serializer = DrinkSerializer(drinks, many=True) return Response(serializer.data) class drink_detail(APIView): def get(self, request, id=None): drinks = Drink.objects.filter(id=id) serializer = DrinkSerializer(drinks, many=True) return Response(serializer.data)
Create urls.py file app core and register in main urls.py file
urls.py – main
from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('core.urls')), ]
from django.urls import path,include from . import views urlpatterns = [ path('',views.drink_list.as_view()), path('<int:id>/',views.drink_detail.as_view()), ]
Run the Django server:
python manage.py runserver
Now, we’re ready for the first test. Navigate to
http://127.0.0.1:8000. Make sure you’re logged in with your superuser credentials:
and it will provide the output containing 3 different types of objects that the information we are entered through admin panel
Now, if you navigate to
http://127.0.0.1:8000/<id>/, it will show the detail API view page. Notice that you correctly navigate to a valid ID. In the screenshot below, I used 1 as the ID:
Congratulations! You’ve successfully built your first fully functional CRUD Django REST API.
Building a RESTful API can be complicated, but Django REST framework handles complexity fairly 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!