Reader small image

You're reading from  Web Development with Django

Product typeBook
Published inFeb 2021
Reading LevelIntermediate
PublisherPackt
ISBN-139781839212505
Edition1st Edition
Languages
Tools
Right arrow
Authors (5):
Ben Shaw
Ben Shaw
author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

Saurabh Badhwar
Saurabh Badhwar
author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

Andrew Bird
Andrew Bird
author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

Bharath Chandra K S
Bharath Chandra K S
author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

Chris Guest
Chris Guest
author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest

View More author details
Right arrow

12. Building a REST API

Overview

This chapter introduces REST APIs and Django REST Framework (DRF). You will start by implementing a simple API for the Bookr project. Next, you will learn about the serialization of model instances, which is a key step in delivering data to the frontend side of Django applications. You will explore different types of API views, including both functional and class-based types. By the end of this chapter, you will be able to implement custom API endpoints, including simple authentication.

Introduction

In the previous chapter, we learned about templates and class-based views. These concepts greatly help expand the range of functionalities we can provide to the user on the frontend (that is, in their web browser). However, that is not sufficient to build a modern web application. Web apps typically have the frontend built with an entirely separate library, such as ReactJS or AngularJS. These libraries provide powerful tools for building dynamic user interfaces; however, they do not communicate directly with our backend Django code or database. The frontend code simply runs in the web browser and does not have direct access to any data on our backend server. Therefore, we need to create a way for these applications to "talk" to our backend code. One of the best ways to do this in Django is by using REST APIs.

API stands for Application Programming Interface. APIs are used to facilitate interaction between different pieces of software, and they communicate...

REST APIs

REST stands for Representational State Transfer. Most modern web APIs can be classified as REST APIs. REST APIs are simply a type of API that focuses on communicating and synchronizing the state of objects between the database server and frontend client.

For example, imagine that you are updating your details on a website for which you are signed into your account. When you go to the account details page, the web server tells your browser about the various details attached to your account. When you change the values on that page, the browser sends back the updated details to the web server and tells it to update these details on the database. If the action is successful, the website will show you a confirmation message.

This is a very simple example of what is known as decoupled architecture between frontend and backend systems. Decoupling allows greater flexibility and makes it easier to update or change components in your architecture. So, let's say you want...

Serializers

By now, we are well versed in the way Django works with data in our application. Broadly, the columns of a database table are defined in a class in models.py, and when we access a row of the table, we are working with an instance of that class. Ideally, we often just want to pass this object to our frontend application. For example, if we wanted to build a website that displayed a list of books in our Bookr app, we would want to call the title property of each book instance to know what string to display to the user. However, our frontend application knows nothing about Python and needs to retrieve this data through an HTTP request, which just returns a string in a specific format.

This means that any information translated between Django and the frontend (via our API) must be done by representing the information in JavaScript Object Notation (JSON) format. JSON objects look similar to a Python dictionary, except there are some extra rules that constrict the exact syntax...

ViewSets

We have seen how we can optimize our code and make it more concise using class-based generic views. Viewsets and Routers help us further simplify our code. As the name indicates, viewsets are a set of views represented in a single class. For example, we used the AllBooks view to return a list of all books in the application and the BookDetail view to return the details of a single book. Using viewsets, we could combine both these classes into a single class.

DRF also provides a class named ModelViewSet. This class not only combines the two views mentioned in the preceding discussion (that is, list and detail) but also allows you to create, update, and delete model instances. The code needed to implement all this functionality could be as simple as specifying the serializer and queryset. For example, a view that allows you to manage all these actions for your user model could be defined as tersely as the following:

class UserViewSet(viewsets.ModelViewSet):
  ...

Routers

Routers, when used along with a viewset, take care of automatically creating the required URL endpoints for the viewset. This is because a single viewset is accessed at different URLs. For example, in the preceding UserViewSet, you would access a list of users at the URL /api/users/, and a specific user record at the URL /api/users/123, where 123 is the primary key of that user record. Here is a simple example of how you might use a router in the context of the previously defined UserViewSet:

from rest_framework import routers
router = routers.SimpleRouter()
router.register(r'users', UserViewSet)
urlpatterns = router.urls

Now, let's try to combine the concepts of routers and viewsets in a simple exercise.

Exercise 12.04: Using ViewSets and Routers

In this exercise, we will combine the existing views to create a viewset and create the required routing for the viewset:

  1. Open the file bookr/reviews/serializers.py, remove the pre-existing code...

Authentication

As we learned in Chapter 9, Sessions and Authentication, it is important to authenticate the users of our application. It is good practice to only allow those users who have registered in the application to log in and access information from the application. Similarly, for REST APIs too, we need to design a way to authenticate and authorize users before any information is passed on. For example, suppose Facebook's website makes an API request to get a list of all comments for a post. If they did not have authentication on this endpoint, you could use it to programmatically get comments for any post you want. They obviously don't want to allow this, so some sort of authentication needs to be implemented.

There are different authentication schemes, such as Basic Authentication, Session Authentication, Token Authentication, Remote User Authentication, and various third-party authentication solutions. For the scope of this chapter, and for our Bookr application...

Summary

This chapter introduced REST APIs, a fundamental building block in most real-world web applications. These APIs facilitate communication between the backend server and the web browser, so they are central to your growth as a Django web developer. We learned how to serialize data in our database so that it can be transmitted via an HTTP request. We also learned the various options DRF gives us to simplify the code we write, taking advantage of the existing definitions of the models themselves. We also covered viewsets and routers, and saw how they can be used to condense code even further by combining the functionality of multiple views. We also learned about authentication and authorization and implemented token-based authentication for the book review app. In the next chapter, we will extend Bookr's functionality for its users by learning how to generate CSVs, PDFs, and other binary filetypes.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Web Development with Django
Published in: Feb 2021Publisher: PacktISBN-13: 9781839212505
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (5)

author image
Ben Shaw

Ben Shaw is a software engineer based in Auckland, New Zealand. He has worked as a developer for over 14 years and has been building websites with Django since 2007. In that time, his experience has helped many different types of companies, ranging in size from start-ups to large enterprises. He is also interested in machine learning, data science, automating deployments, and DevOps. When not programming, Ben enjoys outdoor sports and spending time with his partner and son.
Read more about Ben Shaw

author image
Saurabh Badhwar

Saurabh Badhwar is an infrastructure engineer who works on building tools and frameworks that enhance developer productivity. A major part of his work involves using Python to develop services that scale to thousands of concurrent users. He is currently employed at LinkedIn and works on infrastructure performance tools and services.
Read more about Saurabh Badhwar

author image
Andrew Bird

Andrew Bird is the data and analytics manager of Vesparum Capital. He leads the software and data science teams at Vesparum, overseeing full-stack web development in Django/React. He is an Australian actuary (FIAA, CERA) who has previously worked with Deloitte Consulting in financial services. Andrew also currently works as a full-stack developer for Draftable Pvt. Ltd. He manages the ongoing development of the donation portal for the Effective Altruism Australia website on a voluntary basis. Andrew has also co-written one of our bestselling titles, "The Python Workshop".
Read more about Andrew Bird

author image
Bharath Chandra K S

Bharath Chandra K S lives in Sydney, Australia, and has over 14 years of software industry experience. He is very passionate about software development on the Python stack, including frameworks such as Flask and Django. He has experience working with both monolithic and microservice architectures and has built various public-facing applications and data processing backend systems. When not cooking up software applications, he likes to cook some nice food.
Read more about Bharath Chandra K S

author image
Chris Guest

Chris Guest is based in Melbourne and started programming in Python 24 years ago, when it was an obscure academic language. He has since used his Python knowledge in the publishing, hospitality, medical, academic and financial sectors. Throughout his career, he has worked with many Python web development frameworks, including Zope, TurboGears, web2py, and Flask, although he still prefers Django.
Read more about Chris Guest