Django for APIs /

Introduction

Course Contents
  • Changelog
  • Introduction
  • Chapter 1: Initial Set Up
  • Chapter 2: Web APIs
  • Chapter 3: Library Website
  • Chapter 4: Library API
  • Chapter 5: Todo API
  • Chapter 6: Todo Vue Frontend
  • Chapter 7: Permissions
  • Chapter 8: Permissions
  • Chapter 9: User Authentication
  • Chapter 10: Viewsets and Routers
  • Chapter 11: Schemas and Documentation
  • Conclusion

In this book, you will learn how to build multiple web APIs with increasing complexity using Django and Django REST Framework. Django is a very popular Python-based web framework that handles the challenging parts of creating a website: authentication, connecting to a database, logic, security, and so on. There are also thousands of third-party packages that add functionality to Django itself, the most prominent of which is Django REST Framework, which allows developers to transform any existing Django project into a powerful web API.

Django and Django REST Framework are used by the largest tech companies in the world, including Instagram, Mozilla, and Pinterest. But they are also well-suited to beginners or weekend side projects because Django's "batteries-included" approach masks much of the underlying complexity, allowing for rapid and secure development. By the end of this book, you will be able to create production-ready web APIs with a small amount of code in an even smaller amount of time.

Prerequisites

If you're new to web development with Django, I recommend starting with my book Django for Beginners, which covers the fundamentals of Django, including models, views, URLs, and templates. The first several chapters are free online and cover proper setup, a Hello World app, a Pages app, and a Message Board app. The full-length version covers a Blog website with forms and user accounts and a production-ready Newspaper site that features a custom user model, complete user authentication flow, emails, permissions, deployment, environment variables, and more.

It is also recommended that readers have a basic knowledge of Python. Truly mastering Python takes years, but with just a little knowledge, you can dive right in and start building things.

Django REST Framework

Somewhat surprisingly for such a popular web framework, Django does not ship with a built-in way to create APIs. Instead, it relies on Django REST Framework (DRF), a third-party package created by Tom Christie and maintained by a team of developers.

DRF integrates seamlessly with Django's core features of models, views, and URLs and adds two of its own to create powerful RESTful APIs:

  1. DRF Serializers convert Django QuerySets and model instances into a data format that is easy to consume over the internet, typically JSON or XML. It is also possible to "deserialize" data—literally the same process in reverse—whereby data is first validated, transformed into a Python dictionary, and then back into a Django QuerySet.
  2. DRF Views are similar to traditional Django views, except they work with serializers to expose URLs. DRF also comes with Viewsets and Routers to handle common use cases, similar to Generic Class-Based Views in Django.

There are thousands of third-party packages available for Django--you can see a complete, searchable list over at Django Packages as well as a curated list in the awesome-django repo--but amongst all of them, Django REST Framework is by far the most popular.

Over the years, several popular third-party packages have migrated into the Django core codebase, and I suspect this will eventually happen for Django REST Framework, too. But for now, be aware that Django REST Framework is technically separate from Django itself but, practically speaking, is inseparable. Django REST Framework has been around for years and is mature, testable, full of features, customizable, and extremely well-documented. It has regular updates that track Django updates, and its core team of developers works closely with Django developers.

REST APIs

An API (Application Programming Interface) is a set of rules defining how two computers can connect and communicate. REpresentational State Transfer (REST) is an architecture style that provides standards between computer systems on the World Wide Web that Roy Fielding first proposed in his 2000 dissertation thesis. A REST API--sometimes referred to as "RESTful"--must meet specific criteria.

  1. Client/Server Separation: The client and server applications are independent.
  2. Stateless: Each request/response pair is independent of the previous one; there is no stored memory of past interactions.
  3. Uniform Interface: All API endpoints are accessible by the same approach and belong to only one uniform resource identifier (URI).

When Django was first released in 2005, most websites had a large monolithic codebase that generated server-side templates. Django also adopted this pattern. When a user request is made, Django's templating engine processes templates on the server to dynamically generate HTML before sending it to the client.

Nowadays, it is far more common for websites to adopt an API-first approach to formally separate the back and front ends. This approach adds some complexity but comes with considerable benefits. A single backend API can support a JavaScript frontend such as Vue, React, or Angular, and it can also power a mobile app written in Java for Android or Swift for iOS. In other words, one Django backend can support three different frontends written in three different programming languages. That's quite powerful!

Growing websites can also benefit from creating an external API that allows third-party developers to build their own iOS or Android apps. When I worked at Quizlet, a popular education website, back in 2010, we did not have the resources to develop our own iOS or Android apps, but we did have an external API available that more than 30 developers used to create flashcard apps powered by the Quizlet database. Several of these apps were downloaded over a million times, enriching the developers and increasing the reach of Quizlet at the same time.

The major downside to an API-first approach is that it requires more configuration than a traditional Django application. However, as we will see in this book, the fantastic Django REST Framework library removes much of that complexity.

Why this book

I wrote this book because there is a distinct lack of good resources for developers new to Django REST Framework. The assumption seems to be that everyone already knows all about APIs, HTTP, REST, and the like. My own journey in learning how to build web APIs was frustrating--and I already knew Django well enough to write a book on it! This book is the guide I wish existed when starting out with Django REST Framework.

Chapter 1 covers the initial setup of installing Python, Django, and Git, as well as working with the command line. Chapter 2 is an introduction to web APIs and the HTTP protocol that underpins it all. In Chapters 3-4, we review the differences between traditional Django and Django REST Framework by building out a Library book website and then transforming it into an API, complete with tests. In Chapter 5, we build and test a Todo API with list and detail API endpoints while learning about Cross-Origin Resource Sharing (CORS) and Cross-Site Request Forgery (CSRF). Then, in Chapter 6, we add a Vue frontend on a separate port that can consume our Todo API endpoints.

Chapter 7 is the start of a making a production-ready Blog API that uses a custom user model and full Create-Read-Update-Delete (CRUD) functionality. Chapters 8 focuses on permissions, appropriately limiting access, and creating a custom permission class. In Chapter 9, the focus turns to user authentication and the four built-in authentication methods. Then, we add endpoints for user registration (signup), login, logout, password reset, and password reset confirmation. Chapter 10 turns to viewsets and routers, built-in components that can greatly reduce the amount of coding required for standard API endpoints. The final chapter, Chapter 11, covers schema and documentation.

The complete source code for all chapters can be found online on GitHub.

Conclusion

Django and Django REST Framework is a powerful and accessible way to build web APIs. By the end of this book, you will be able to add APIs to any existing Django projects or build your own dedicated web API from scratch properly using modern best practices. Let's begin!