How to Create a basic API using Django Rest Framework ?

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.

This article revolves around how to create a basic API using Django REST Framework. It assumes you are familiar with Django basics – Django tutorial. Also, installation of Django REST Framework. Assuming you have created a project named geeksforgeeks with Django, let’s initiate Django REST Framework.

Steps

Add rest_framework to INSTALLED_APPS

To initialize REST Framework in your project, go to settings.py, and in INSTALLED_APPS add ‘rest_framework’ at the bottom.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Application definition
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]

chevron_right


Create a app and model

Now, let’s create a app using command,

python manage.py startapp apis

A folder with name apis would have been registered by now. let’s add this app to INSTALLED_APPS and urls.py also.
In, settings.py,



filter_none

edit
close

play_arrow

link
brightness_4
code

# Application definition
  
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'apis',
]

chevron_right


Now, add apis urls in urls.py. In geeksforgeeks.urls.py,

filter_none

edit
close

play_arrow

link
brightness_4
code

from django.contrib import admin
# include necessary libraries
from django.urls import path, include
  
urlpatterns = [
    path('admin/', admin.site.urls),
    # add apis urls
    path('', include("apis.urls"))
]

chevron_right


Create a model
To demonstrate, creating and using an API, let’s create a model named “GeeksModel”. In apis/models.py

filter_none

edit
close

play_arrow

link
brightness_4
code

from django.db import models
  
class GeeksModel(models.Model):
    title = models.CharField(max_length = 200)
    description = models.TextField()
  
    def __str__(self):
        return self.title

chevron_right


now our app is ready, let’s serialize the data and create views from the same.

Serialization

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, in file apis/serializers.py,

filter_none

edit
close

play_arrow

link
brightness_4
code

# import serializer from rest_framework
from rest_framework import serializers
  
# import model from models.py
from .models import GeeksModel
  
# Create a model serializer 
class GeeksSerializer(serializers.HyperlinkedModelSerializer):
    # specify model and fields
    class Meta:
        model = GeeksModel
        fields = ('title', 'description')

chevron_right


Creating a viewset

To render data into frontend, and handle requests from user, we need to create a view. In Django REST Framework, we call these as viewsets, so let’s create a view in apis/views.py,

filter_none

edit
close

play_arrow

link
brightness_4
code

# import viewsets
from rest_framework import viewsets
  
# import local data
from .serializers import GeeksSerializer
from .models import GeeksModel
  
# create a viewset
class GeeksViewSet(viewsets.ModelViewSet):
    # define queryset
    queryset = GeeksModel.objects.all()
      
    # specify serializer to be used
    serializer_class = GeeksSerializer

chevron_right


Define URLs of API

Specify the url path of APIs to be accessed, In apis/urls.py,

filter_none

edit
close

play_arrow

link
brightness_4
code

# basic URL Configurations
from django.urls import include, path
# import routers
from rest_framework import routers
  
# import everything from views
from .views import *
  
# define the router
router = routers.DefaultRouter()
  
# define the router path and viewset to be used
router.register(r'geeks', GeeksViewSet)
  
# specify URL Path for rest_framework
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls'))
]

chevron_right


After everything is sucessfully ready, let’s run some commands to activate the server.

Run server and check API

Run following commands to create the database, and run server,

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Now visit http://127.0.0.1:8000/geeks/,
Create-a-basic-API-with-Django-REST-Framework

To check the code for the project, click here

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Software Developer at GeeksForGeeks

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.