How to Create a API using Django Rest Framework?

Published On: 25/07/2022 | Category: Django Python

Hi Dev,

Here, I will show you how to create a api using django rest framework. We will look at example of django rest api example. you will learn django rest framework post example. I would like to show you django rest api tutorial.

Here i explained Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds. There are three stages before creating a API through REST framework, Converting a Model’s data to JSON/XML format (Serialization), Rendering this data to the view, Creating a URL for mapping to the viewset.

While Django does a lot of heavy lifting by connecting it’s models to the database, serializing those models into a JSON format is still a big challenge. DRF complements Django by providing a means of converting it’s models to a REST-full format.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python startapp rest_api
Step 3 : Install a Django REST Framework

First of all let’s install django and djangorestframework which are the necessary Python libraries.

pip install djangorestframework
Step 4 : Update

In this step we require to do two things in our file, One is our installed app name and another one is installed rest_framework Add the below lines to your file:

Next, you need to add it in the file as follows:
Step 5 : Database Setup

Next step, we will modify the file and update the database settings to configure the mydb database:
    'default': {  
        'ENGINE': 'django.db.backends.mysql',  
        'NAME': 'example',  
Step 6: Create a Model

In this step we will require the database model for storing contacts.Open the rest_api/ file and add the following code:

from django.db import models

# Create your models here.

class Blog(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()

After creating these model, you need to create migrations using the following command:

Step 7 : Create a Migrations
python makemigrations

After successfully run the above command go to the rest_api/migrations/

# Generated by Django 3.1.7 on 2022-07-22 13:55

from django.db import migrations, models

class Migration(migrations.Migration):

    initial = True

    dependencies = [

    operations = [
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('title', models.CharField(max_length=100)),
                ('description', models.TextField()),

Next, you need to migrate your database using the following command:

python migrate
Step 8 : Creating the Serializers

In this step, we need to create 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. Let’s start creating a serializer.

from rest_framework import serializers

from core.models import Blog

class BlogSerializer(serializers.ModelSerializer):
    class Meta:
        model = Blog
        fields = ('title', 'description')
Step 9 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the rest_api/ file and add:

from rest_framework import viewsets

from core.serializers import BlogSerializer
from core.models import Blog

class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
Step 10 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the rest_api/ file and update it as follows:

from django.urls import include, path

from rest_framework import routers

from core.views import BlogViewSet

router = routers.DefaultRouter()
router.register('blogs', BlogViewSet)

urlpatterns = [
    path('', include(router.urls)),

Next, we will require the modify the your root preoject folder lets update the file.

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

urlpatterns = [
    path('', include('rest_api.urls')),
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000/blogs/ address with a web browser.

I Hope It will help you....