REST (REpresentational State Transfer) is a beautiful way for building web APIs and Django REST framework elegantly supports building REST service. To begin with Django you can refer to another post Django - Initial Setup.
Step 0 is to install Django REST Framework (DRF).
>> pip install djangorestframework
Make an entry into INSTALLED_APPS in settings.py of 'rest_framework' and we are good to start.
Create a new app library >> python manage.py startapp library and make its entry into INSTALLED_APPS as 'library'.
In models.py
In models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=100) country = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=100) publisher = models.CharField(max_length=50) price = models.FloatField() author = models.ForeignKey("Author")
So here we are creating a small relation of the following type.
Execute following commands to get these models created as tables in SQLite database.
>> python manage.py makemigrations
>> python manage.py syncdb
I have created one entry into each table (library_Book and library_Author) using SQLite Browser for demonstration.
These records along with certain calculated fields need be exposed as JSON to the clients. For which create serializers.py inside library app and add the following code.
Execute following commands to get these models created as tables in SQLite database.
>> python manage.py makemigrations
>> python manage.py syncdb
I have created one entry into each table (library_Book and library_Author) using SQLite Browser for demonstration.
These records along with certain calculated fields need be exposed as JSON to the clients. For which create serializers.py inside library app and add the following code.
from library.models import Book, Author from rest_framework import serializers class AuthorSerializer(serializers.ModelSerializer): """ Serializing all authors """ class Meta: model = Author fields = ('name', 'country') class BookSerializer(serializers.ModelSerializer): """ Serializing all books """ author = AuthorSerializer(many=False) search_url = serializers.SerializerMethodField() pack_of_10_cost = serializers.SerializerMethodField() class Meta: model = Book fields = ('id', 'title', 'publisher', 'price', 'pack_of_10_cost', 'search_url', 'author') def get_search_url(self, obj): return "http://www.isbnsearch.org/isbn/{}".format(obj.id) def get_pack_of_10_cost(self, obj): return (obj.price*10*0.5)
We have created AuthorSerializer and BookSerializer classes. Inside that defined Meta class providing it model name and fields to send as JSON data.
In the BookSerializer class, we want to add 3 extra fields.
model's serializer_class and the queryset.
Create urls.py class in the library app, and add the following url mappings.
In the BookSerializer class, we want to add 3 extra fields.
- author - it should show data of the book's Author which is achieved by providing AuthorSerializer class.
- search_url, pack_of_10_cost - These are calculated fields, DRF automatically checks for methods prefixed with get_ in the same class to get the values of these fields.
from django.shortcuts import render from library.models import Book, Author from rest_framework import generics from library.serializers import BookSerializer, AuthorSerializer class BookList(generics.ListAPIView): """ Returns list of all books """ serializer_class = BookSerializer queryset = Book.objects.all() class AuthorList(generics.ListAPIView): """ Returns list of all authors """ serializer_class = AuthorSerializer queryset = Author.objects.all()We are using class-based views, which inherit generics.ListAPIView. In this class we need to specify
model's serializer_class and the queryset.
Create urls.py class in the library app, and add the following url mappings.
from django.conf.urls import url from library.views import BookList, AuthorList urlpatterns = ( url(r'^books/$', BookList.as_view(), name="book-list"), url(r'^authors/$', AuthorList.as_view(), name="author-list") )
Make the following url mapping entry in urls.py of the project.
url(r'^library/', include('library.urls'))
We are all set. Now start the server and hit the URLs to see the results.
We have seen how we can list the records and send them as JSON over the wire. In the next post we will learn how to perform CRUD (create-retrieve-update-delete) operations using DRF.
No comments:
Post a Comment
Your comments are very much valuable for us. Thanks for giving your precious time.