Tuesday, June 9, 2020

Django Rest Framework:

Django Rest Framework(DRF):

Django Rest Framework(DRF) is an application used to build RESTful API based on Django models.

In a RESTful API, endpoints(URLs) define the structure of API and how end user access data from our application using HTTP methods like GET, POST, PUT, DELETE etc..

 

Requirements:

In my case,

Python 3.8

Django 3.0

·        Create a Django project and app

cd ~
django-admin startproject local-librari-api
cd local-library-api
python manage.py startapp catalogapp

Create and activate virtual environment and install rest framework as fallows 

Installation:

·        Installing with pip:

pip install djangorestframework

djangorestframework==3.11.0

·        Go to Django project -> settings.py and add ‘rest_framework’ to INSTALLED_APPS

INSTALLED_APPS = [
   
'catalogapp',
   
'rest_framework',
]

 

·        And then create models for the app to work in cataogapp/models.py module

from django.db import models


class Genre(models.Model):
   
"""Model representing a book genre."""
   
    

class Book(models.Model):
   
"""Model representing a book (but not a specific copy of a book)."""
   
title = models.CharField(max_length=200)

    author = models.ForeignKey(
'Author', on_delete=models.SET_NULL)

    summary = models.TextField(
max_length=1000)
    isbn = models.CharField(max_length=13,)    
   
genre = models.ManyToManyField(Genre)
   
    language = models.ForeignKey('Language', on_delete=models.SET_NULL)

   
def __str__(self):
       
"""String for representing the Model object."""
       
return self.title



class BookInstance(models.Model):
   
   

class Author(models.Model):
   
"""Model representing an author."""

class Language(models.Model):
etc……

·        Now create initial migrations and sync database as fallows..

 

(venv) C:\Users\local-library-api>python manage.py makemigrations

(venv) C:\Users\local-library-api>python manage.py makemigrations

 

Creating serializer class:

-         In order to work with REST API, we need to convert model objects into some other format like JSON.

-         We can do this by importing serializers module from djangorestframework.

-         Now create a file named serializers.py in catalogapp directory … like catalogapp/serializers.py

from rest_framework import serializers
from catalogapp import Book, Authors


class BookSerializer(serializers.Serializer):
    title = CharField(
max_length=200)
    author = PrimaryKeyRelatedField(
allow_null=True, queryset=Author.objects.all(), required=False)
    summary = CharField(
max_length=1000, style={'base_template': 'textarea.html'})
    isbn = CharField(
label='ISBN', max_length=13)
    genre = PrimaryKeyRelatedField(
allow_empty=False, many=True, queryset=Genre.objects.all())
    language = PrimaryKeyRelatedField(
allow_null=True, queryset=Language.objects.all(), required=False)

Working with API is very similar to Django forms

Using ModelSerializer class:

Django provides both Serializer and ModelSerializer classes

ModelSerializer class automatically determines the model fields and implements the create() and update() methods. This is short-cut for creating serializers for models.

Modify the above code in serializers.py module as fallows…

class BookSerializer(serializers.ModelSerializer):
   
class Meta:
        model = Book
        fields = [
………. Enter field names here ………..]

with serializer instance, you can see the implementation of serializer…just say

print(repr(serializer instance))

Django views using serializer:

Now write some views using serializer class in catalogapp/views.py module

For example to view all the books in the library

from catalogapp.models import Book
from catalogapp.serializers import BookSerializer
from django.http import JsonResponse
from rest_framework.parsers import JSONParser
 
def book_list_view(request):
   
if request.method == 'GET':
        books = Book.objects.all()
        serializer = BookSerializer(books
, many=True)
       
return JsonResponse(serializer.data, safe=False)
   
elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = BookSerializer(
data=data)
       
if serializer.is_valid():
            serializer.save()
           
return JsonResponse(serializer.data, status=201)
       
return JsonResponse(serializer.errors, status=400)

 

finally we have to map these view in the catalogapp/urls.py module

urlpatterns = [
   

   
path('books/', views.book_list_view, name='books'),

]

 

·        Add the fallowing to root urls.py file…. local-library-api/urls.py

 

urlpatterns = [
   

   
path('catalogapp/', include('catalogapp.urls')),
]

 

 

 

 


No comments:

Post a Comment