Django Rest Framework

Django uses rest_framework app to make GET, POST, PUT and DELETE requests using an API endpoint. To install Django Rest Framework simply run:

pip install djangorestframework

Setting up Rest Framewor in Djangok

After installation simply add rest_framework in setting.py:

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

Rest API Sample Project

In the sample project we have an app with Blog model and title, author fields:

models.py:

    from django.db import models
    
    class Blog(models.Model):
    	title = models.CharField(max_length=120)
    	author = models.CharField(max_length=60)
    	def __str__(self):
    		return self.title
                                

project > urls.py:

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('myapp/', include('myapp.urls')),
        path('rest_framework/', include('rest_framework.urls')),
    ]
                                

app> urls.py:

    from rest_framework import routers
    from django.urls import path, include
    from . import views
    
    router = routers.DefaultRouter()
    router.register('', views.BlogView)
    
    urlpatterns = [
        path('', views.index),
        path('api/', include(router.urls)),
    ] 
                                

app > serializers.py: This file needs to be created manually under the app folder.

    from rest_framework import serializers
    from .models import Blog
    
    class BlogSerializer(serializers.HyperlinkedModelSerializer):
    	class Meta:
    		model = Blog
    		fields = ('id', 'url', 'title', 'author')
                                

views.py:

    from django.shortcuts import render
    from rest_framework import viewsets
    from .models import Blog
    from .serializers import BlogSerializer
    
    def index(request):
    	return render(request, 'index.html', {})
    
    class BlogView(viewsets.ModelViewSet):
    	queryset = Blog.objects.all()
    	serializer_class = BlogSerializer
                                

To run visit 127.0.0.1:8000/myapp/api/


Rest Rest API Post Request

Django Rest Framework POST Request

Rest Rest API GET, PUT, DELETE Request

Django Rest Framework GET Request

Rest Rest API Permissions

Finallay, to make the APT endpoint secure we must add API permissions in settings.py. API Permissions are:

  • AllowAny
  • IsAuthenticated
  • IsAuthenticatedOrReadOnly
  • IsAdminUser
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES' : 
        ('rest_framework.permissions.IsAuthenticated',)
    }