Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Becoming an Enterprise Django Developer

You're reading from  Becoming an Enterprise Django Developer

Product type Book
Published in Jun 2022
Publisher Packt
ISBN-13 9781801073639
Pages 526 pages
Edition 1st Edition
Languages
Author (1):
Michael Dinder Michael Dinder
Profile icon Michael Dinder

Table of Contents (15) Chapters

Preface 1. Part 1 – Starting a Project
2. Chapter 1: Undertaking a Colossal Project 3. Chapter 2: Project Configuration 4. Chapter 3: Models, Relations, and Inheritance 5. Part 2 – Django Components
6. Chapter 4: URLs, Views, and Templates 7. Chapter 5: Django Forms 8. Chapter 6: Exploring the Django Admin Site 9. Chapter 7: Working with Messages, Email Notifications, and PDF Reports 10. Part 3 – Advanced Django Components
11. Chapter 8: Working with the Django REST Framework 12. Chapter 9: Django Testing 13. Chapter 10: Database Management 14. Other Books You May Enjoy

Chapter 8: Working with the Django REST Framework

This chapter will focus on working with an Application Programming Interface (API). An API is actually a set of tools and communication protocols working to allow two different applications to communicate with each other effectively; it is what acts as the middleman between two systems. A REST API adopts the design principles set forth in a Representational State Transfer (REST) software architecture and is most commonly used with web-based applications. Every time we mention the word API in this chapter, we are really referring to a REST API as they are technically slightly different but usually interpreted as the same thing.

Django itself relies on third-party packages to work with an existing API or to create an API yourself. A common Python package that is available is called the requests package. The requests package is used to send and receive requests to and from an existing API found on the server side. More information...

Technical requirements

To work with the code in this chapter, the following tools will need to be installed on your local machine:

  • Python version 3.9 – used as the underlying programming language for the project
  • Django version 4.0 – used as the backend framework of the project
  • pip package manager – used to manage third-party Python/Django packages

We will continue to work with the solution created in Chapter 2, Project Configuration. However, it is not necessary to use the Visual Studio IDE. The main project itself can be run using another IDE or run independently using a terminal or command-line window from within the project root folder, which is where the manage.py file resides. Whatever editor or IDE you are using, a virtual environment will also be needed to work with the Django project. Instructions for how to create a project and virtual environment can be found in Chapter 2, Project Configuration. You will need a database to store...

Preparing for this chapter

Start by creating a new app in your project called chapter_8 by following the steps discussed in Chapter 2, Project Configuration, in the subsection titled Creating a Django app. As discussed in that section, don’t forget to change the value of the name = variable for your app class found in the /becoming_a_django_entdev/becoming_a_django_entdev/chapter_8/apps.py file to now point to the path where you installed your app. Be sure to also include this app in the INSTALLED_APPS variable found in the settings.py file as well.

In the main urls.py file of the site, add the following path, which points to the URL patterns of this chapter that we will be creating:

# /becoming_a_django_entdev/urls.py
...
urlpatterns = [
    path(
        ‘’, 
        include(
          &...

Serializing objects

Creating an API starts with creating a serializer class and then creating a view, in particular a ModelViewSet view class. Serializing objects means converting a model object into JSON format to represent the data of that object. The last thing we need to do is create URL patterns that map to the view classes that we wrote; this will be done using URL routers. These URL patterns are considered your API endpoints.

One thing to note in this section is that we need to create serializers for all models that relate to other models when using related fields. This is why the following exercises will show examples for all four models of the chapter_3 app. This has to be done in order to ensure that we do not get errors when using the Browsable API, which we will introduce later in this chapter, and when performing API requests. This means if you have multiple Seller that have been assigned a Group or Permission, that Group and/or Permission object will also have to be...

Using the Browsable API

The Browsable API is a built-in tool that allows for easy browsing and testing of your API. It allows us to read and view data in JSON and API format. This section will teach us how to use and access this tool. When we added the chapter-8 path to the URL routers in the previous section, we activated that path as what is called the API root, which provides all of the URLs available in your API, with some exceptions. Visit http://localhost:8000/chapter-8/ to see these URLs, as depicted here:

Figure 8.2 – The Browsable API – API root

When building custom API endpoints, as we will do later in this chapter, you will likely not see them displayed in your API root. You’ll see that the serializers for the groups, permissions, and content types have all been included with the code of this book. There is a dropdown at the top right of every main router path that we created, to switch between the two formats, API and JSON,...

Building SPA-like pages

Single-Page App (SPA) pages are web pages where content gets updated within containers/nodes rather than reloading or redirecting the page to display that data. Usually, some of the work of the server is offloaded to the client’s browser to perform these requests and/or render the HTML, usually with JavaScript or jQuery. When an event is triggered, such as the clicking of a button or submission of a form, JavaScript is used to obtain the data from the server and then render that content onto the page, wherever we want it to display.

In this exercise, we will use the API endpoint of the Seller created by the router, at http://localhost:8000/chapter-8/sellers/1/, to render JSON as a string within a container found in the body of a query page. The query page is just a standard page that uses JavaScript to communicate with an API endpoint.

Creating the view

In this subsection, we will build the view to handle a page where the user can enter a number...

Writing custom API endpoints

Creating our own API endpoints is just as easy as writing another URL pattern. This section will teach us how to write our own API endpoints and practice sending preformatted HTML back to the client. You do not need to create all custom API endpoints to return preformatted HTML but we will practice doing that. Preformatting HTML only works well if the app communicating with your API does not need to restructure or restyle the HTML in any way after it has been received. This means the server/developer needs to know exactly how the client will use the data that it receives. No more JavaScript will be needed other than what was already written in the $gotoSPA_Page() function of the previous exercise. We will reuse that same function and just alter one or two things before we move forward. We will create a new view class and add permission logic to secure that endpoint from unwanted users accessing the API.

Let’s begin working on this exercise in...

Authenticating with tokens

In this exercise, we will be treating the API that we built earlier in this chapter as if it is now an API provided by a third party. Pretend for a moment that you did not build your API and we will practice authenticating by using a security token. Token security will be used in addition to the individual model permissions as we did in the previous exercise. This will be done whether you grant a user access to the Django admin site or not. That also means we will create a new user/seller for this exercise and then restrict that user’s access to the Django admin site for demonstration purposes.

We will follow the same steps as the previous two exercises next.

Project configuration

This exercise requires a little bit of configuration inside the project’s settings.py file before we can get started with the same steps as before.

Follow these steps to configure your project:

  1. In your settings.py file, add the following app to...

Summary

The examples provided throughout this chapter demonstrate a simple way to construct and work with your newly created API, in a variety of ways! If you want to give your app an SPA-like feel, the simplest implementation is to use the vanilla JavaScript fetch() function or the jQuery ajax() function. Instead of writing your own actions with either of these two functions, you could settle upon using a JavaScript-based framework, such as React, AngularJS, or Vue.js, just to name a few. The JavaScript-based frameworks can format and style your HTML on the client side. One of the template-based approaches provided in this chapter also demonstrates how this work can be transferred from the client side onto the server side. This provides you with numerous tools in your toolbox, in regard to building and working with an API.

We also learned how to work with authentication tokens and discovered that we can still work with tokens when formatting HTML on the server side. However, the...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Becoming an Enterprise Django Developer
Published in: Jun 2022 Publisher: Packt ISBN-13: 9781801073639
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.
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}