Django for APIs Build Web APIs with Python Django (William S. Vincent) (Z-Library)
Author: William S. Vincent
技术
No Description
📄 File Format:
PDF
💾 File Size:
8.6 MB
50
Views
0
Downloads
0.00
Total Donations
📄 Text Preview (First 20 pages)
ℹ️
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
📄 Page
1
(This page has no text content)
📄 Page
2
Django for APIs Build web APIs with Python and Django William S. Vincent This book is for sale at http://leanpub.com/djangoforapis This version was published on 2019-10-28 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. © 2018 - 2019 William S. Vincent
📄 Page
3
Also ByWilliam S. Vincent Django for Beginners Django for Professionals
📄 Page
4
Contents Introduction 1 Prerequisites 1 Why APIs 2 Django REST Framework 3 Why this book 4 Conclusion 5 Chapter 1: Web APIs 6 World Wide Web 6 URLs 7 Internet Protocol Suite 8 HTTP Verbs 9 Endpoints 10 HTTP 11 Status Codes 13 Statelessness 14 REST 15 Conclusion 15 Chapter 2: Library Website and API 17 Traditional Django 17 First app 21 Models 23
📄 Page
5
CONTENTS Admin 25 Views 29 URLs 30 Webpage 34 Django REST Framework 34 URLs 37 Views 38 Serializers 39 cURL 40 Browsable API 41 Conclusion 43 Chapter 3: Todo API 44 Initial Set Up 44 Models 47 Django REST Framework 51 URLs 53 Serializers 54 Views 56 Consuming the API 57 Browsable API 58 CORS 60 Tests 63 Conclusion 64 Chapter 4: Todo React Front-end 66 Install Node 66 Install React 67 Mock data 69 Django REST Framework + React 74
📄 Page
6
CONTENTS Conclusion 78 Chapter 5: Blog API 79 Initial Set Up 79 Model 80 Tests 84 Django REST Framework 86 URLs 88 Serializers 89 Views 91 Browsable API 92 Conclusion 96 Chapter 6: Permissions 97 Create a new user 97 Add log in to the browsable API 100 AllowAny 105 View-Level Permissions 107 Project-Level Permissions 109 Custom permissions 111 Conclusion 116 Chapter 7: User Authentication 117 Basic Authentication 117 Session Authentication 119 Token Authentication 121 Default Authentication 123 Implementing token authentication 124 Endpoints 128 Django-Rest-Auth 128
📄 Page
7
CONTENTS User Registration 134 Tokens 139 Conclusion 145 Chapter 8: Viewsets and Routers 147 User endpoints 147 Viewsets 153 Routers 154 Conclusion 160 Chapter 9: Schemas and Documentation 162 Schemas 163 Documentation 165 Django REST Swagger 171 Swagger Log In and Log Out 175 Conclusion 176 Conclusion 177 Next Steps 177 Giving Thanks 178
📄 Page
8
Introduction The internet is powered by RESTful APIs. Behind the scenes even the simplest online task involves multiple computers interacting with one another. An API (Application Programming Interface) is a formal way to describe two computers communicating directly with one another. And while there are multiple ways to build an API, web APIs–which allow for the transfer of data over the world wide web–are overwhelmingly structured in a RESTful (REpresentational State Transfer) pattern. In this book you will learn how to build multiple RESTful web APIs of increasing complexity from scratch using Django and Django REST Framework. The combination of Django and Django REST Framework is one of the most popular and customizable ways to build web APIs, used bymany of the largest tech companies in the world including Instagram, Mozilla, Pinterest, and Bitbucket. It is also uniquely well-suited to beginners becauseDjango’s “batteries-included” approachmasksmuch of the underlying complexity and security risks involved in creating any web API. Prerequisites If you’re brand new to web development with Django, I recommend first reading my previous book Django for Beginners. The first several chapters are available for free online and cover proper set up, a Hello World app, Pages app, and a Message Board website. The full-length version goes deeper and covers a Blogwebsite with forms and user accounts as well as a production-ready Newspaper site that features a custom user model, complete user authentication flow, emails, permissions, and more.
📄 Page
9
Introduction 2 This background in traditional Django is important since Django REST Framework deliberately mimics many Django conventions. It is also recommended that readers have a basic knowledge of Python itself. Truly mastering Python takes years, but with just a little bit of knowledge you can dive right in and start building things. Why APIs Djangowas first released in 2005 and at the timemost websites consisted of one large monolithic codebase. The “back-end” consisted of database models, URLs, and views which interacted with the “front-end” templates of HTML, CSS, and JavaScript that controlled the presentational layout of each web page. However in recent years an “API-first” approach has emerged as arguably the dom- inant paradigm in web development. This approach involves formally separating the back-end from the front-end. It means Django becomes a powerful database and API instead of just a website framework. Today Django is arguably used more often as just a back-end API rather than a full monolithic website solution at large companies! An obvious question at this point is, “Why bother?” Traditional Django works quite well on its own and transforming a Django site into a web API seems like a lot of extra work. Plus, as a developer, you then have to write a dedicated front-end in another programming language. This approach of dividing services into different components, by the way, is broadly known as Service-oriented architecture. It turns out however that there are multiple advantages to separating the front-end from the back-end. First, it is arguably muchmore “future-proof” because a back-end
📄 Page
10
Introduction 3 API can be consumed by any JavaScript front-end. Given the rapid rate of change in front-end libraries–React was only released in 2013 and Vue in 2014!–this is highly valuable. When the current front-end frameworks are eventually replaced by even newer ones in the years to come, the back-end API can remain the same. No major rewrite is required. Second, an API can support multiple front-ends written in different languages and frameworks. Consider that JavaScript is used for web front-ends, while Android apps require the Java programming language, and iOS apps need the Swift programming language. With a traditional monolithic approach, a Django website cannot support these various front-ends. But with an internal API, all three can communicate with the same underlying database back-end! Third, an API-first approach can be used both internally and externally. When I worked at Quizlet 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 their own 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. Quizlet is now a top 20 website in the U.S. during the school year. The major downside to an API-first approach is that it requires more configuration than a traditional Django application. However aswewill see in this book, the fantastic Django REST Framework library removes much of this complexity. Django REST Framework There are hundreds and hundreds of third-party apps available that add further functionality to Django. (You can see a complete, searchable list over at Django Packages.) However Django REST Framework is arguably the killer app for Django.
📄 Page
11
Introduction 4 It is mature, full of features, customizable, testable, and extremely well-documented. It also purposefully mimics many of Django’s traditional conventions, which makes learning it much faster. And it is written in the Python programming language, a wonderful, popular, and accessible language. If you already know Django, then learning Django REST Framework is a logical next step. With aminimal amount of code, it can transform any existing Django application into a web API. Why this book I wrote this book because there is a distinct lack of good resources available 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 begins with a brief introduction to web APIs and the HTTP protocol. In Chapter 2 we review the differences between traditional Django and Django REST Framework by building out a Library book website and then adding an API to it. Then in Chapters 3-4 we build a Todo API and connect it to a React front-end. The same process can be used to connect any dedicated front-end—web, iOS, Android, desktop, or other—to a web API back-end. In Chapters 5-9 we build out a production-ready Blog API which includes full CRUD functionality. We also cover in-depth permissions, user authentication, viewsets, routers, documentation, and more. Complete source code for all chapters can be found online on Github.
📄 Page
12
Introduction 5 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 build your own web APIs from scratch properly usingmodern best practices. And you’ll be able to extend any existing Django website into a web API with a minimal amount of code. Let’s begin!
📄 Page
13
Chapter 1: Web APIs Before we start building our own web APIs it’s important to review how the web really works. After all, a “web API” literally sits on top of the existing architecture of theworld wide web and relies on a host of technologies including HTTP, IP/TCP, and more. In this chapterwewill review the basic terminology ofweb APIs: endpoints, resources, HTTP verbs, HTTP status codes, and REST. Even if you already feel comfortable with these terms, I encourage you to read the chapter in full. World Wide Web The Internet is a system of interconnected computer networks that has existed since at least the 1960s. However, the internet’s early usage was restricted to a small number of isolated networks, largely government, military, or scientific in nature, that exchanged information electronically. By the 1980s, many research institutes and universities were using the internet to share data. In Europe, the biggest internet node was located at CERN (European Organization for Nuclear Research) in Geneva, Switzerland, which operates the largest particle physics laboratory in the world. These experiments generate enormous quantities of data that need to be shared remotely with scientists all around the world. Comparedwith today, though, overall internet usage in the 1980s wasminiscule. Most people did not have access to it or even understood why it mattered. A small number of internet nodes powered all the traffic and the computers using it were primarily within the same, small networks.
📄 Page
14
Chapter 1: Web APIs 7 This all changed in 1989when a research scientist at CERN, TimBerners-Lee, invented HTTP and ushered in the modern World Wide Web. His great insight was that the existing hypertext system, where text displayed on a computer screen contained links (hyperlinks) to other documents, could be moved onto the internet. His invention, Hypertext Transfer Protocol (HTTP), was the first standard, universal way to share documents over the internet. It ushered in the concept of web pages: discrete documents with a URL, links, and resources such as images, audio, or video. Today, when most people think of “the internet,” they think of the World Wide Web, which is now the primary way that billions of people and computers communicate online. URLs A URL (Uniform Resource Locator) is the address of a resource on the internet. For example, the Google homepage lives at https://www.google.com. When you want to go to the Google homepage, you type the full URL address into a web browser. Your browser then sends a request out over the internet and ismagically connected (we’ll cover what actually happens shortly) to a server that responds with the data needed to render the Google homepage in your browser. This request and response pattern is the basis of all web communication. A client (typically a web browser but also a native app or really any internet-connected device) requests information and a server responds with a response. Since web communication occurs via HTTP these are known more formally as HTTP requests and HTTP responses. Within a given URL are also several discrete components. For example, consider again https://www.google.com. The first part, https, refers to the scheme used. It tells the
📄 Page
15
Chapter 1: Web APIs 8 web browser how to access resources at the location. For a website this is typically http or https, but it could also be ftp for files, smtp for email, and so on. The next section, www.google.com, is the hostname or the actual name of the site. Every URL contains a scheme and a host. Many webpages also contain an optional path, too. If you go to the homepage for Python at https://www.python.org and click on the link for the “About” page you’ll be redirected to https://www.python.org/about/. The /about/ piece is the path. In summary, every URL like https://python.org/about/ has three potential parts: • a scheme - https • a hostname - www.python.org • and an (optional) path - /about/ Internet Protocol Suite Once we know the actual URL of a resource, a whole collection of other technologies must work properly (together) to connect the client with the server and load an actual webpage. This is broadly referred to as the internet procotol suite and there are entire books written on just this topic. For our purposes, however, we can stick to the broad basics. Several things happen when a user types https://www.google.com into their web browser and hits Enter. First the browser needs to find the desired server, some- where, on the vast internet. It uses a domain name service (DNS) to translate the domain name “google.com” into an IP address, which is a unique sequence of num- bers representing every connected device on the internet. Domain names are used because it is easier for humans to remember a domain name like “google.com” than an IP address like “172.217.164.68”.
📄 Page
16
Chapter 1: Web APIs 9 After the browser has the IP address for a given domain, it needs a way to set up a consistent connection with the desired server. This happens via the Transmission Control Protocol (TCP) which provides reliable, ordered, and error-checked delivery of bytes between two application. To establish a TCP connection between two computers, a three-way “handshake” occurs between the client and server: 1. The client sends a SYN asking to establish a connection 2. The server responds with a SYN-ACK acknowledging the request and passing a connection parameter 3. The client sends an ACK back to the server confirming the connection Once the TCP connection is established, the two computers can start communicating via HTTP. HTTP Verbs Every webpage contains both an address (the URL) as well as a list of approved actions known as HTTP verbs. So far we’vemainly talked about getting aweb page, but it’s also possible to create, edit, and delete content. Consider the Facebook website. After logging in, you can read your timeline, create a new post, or edit/delete an existing one. These four actions Create-Read-Update- Delete are known colloquially as CRUD functionality and represent the overwhelming majority of actions taken online. The HTTP protocol contains a number of request methods that can be used while requesting information from a server. The four most common map to CRUD func- tionality. They are POST, GET, PUT, and DELETE.
📄 Page
17
Chapter 1: Web APIs 10 Diagram CRUD HTTP Verbs ---- ---------- Create <--------------------> POST Read <--------------------> GET Update <--------------------> PUT Delete <--------------------> DELETE To create content you use POST, to read content GET, to update it PUT, and to delete it you use DELETE. Endpoints A website consists of web pages with HTML, CSS, images, JavaScript, and more. But a web API has endpoints instead which are URLs with a list of available actions (HTTP verbs) that expose data (typically in JSON, which is the most common data format these days and the default for Django REST Framework). For example, we could create the following API endpoints for a new website called mysite. Diagram https://www.mysite.com/api/users # GET returns all users https://www.mysite.com/api/users/<id> # GET returns a single user In the first endpoint, /api/users, an available GET request returns a list of all available users. This type of endpoint which returns multiple data resources is known as a collection. The second endpoint /api/users/<id> represents a single user. A GET request returns information about just that one user.
📄 Page
18
Chapter 1: Web APIs 11 If we added POST to the first endpoint we could create a new user, while adding DELETE to the second endpoint would allow us to delete a single user. We will become much more familiar with API endpoints over the course of this book but ultimately creating an API involves making a series of endpoints: URLs with associated HTTP verbs. A webpage consists of HTML, CSS, images, and more. But an endpoint is just a way to access data via the available HTTP verbs. HTTP We’ve already talked a lot about HTTP in this chapter, but here we will describe what it actually is and how it works. HTTP is a request-response protocol between two computers that have an existing TCP connection. The computer making the requests is known as the client while the computer responding is known as the server. Typically a client is a web browser but it could also be an iOS app or really any internet-connected device. A server is a fancy name for any computer optimized to work over the internet. All we really need to transform a basic laptop into a server is some special software and a persistent internet connection. Every HTTP message consists of a request/status line, headers, and optional body data. For example, here is a sample HTTP message that a browser might send to request the Google homepage located at https://www.google.com.
📄 Page
19
Chapter 1: Web APIs 12 Diagram GET / HTTP/1.1 Host: google.com Accept_Language: en-US The top line is known as the request line and it specifies the HTTPmethod to use (GET), the path (/), and the specific version of HTTP to use (HTTP/1.1). The two subsequent lines are HTTP headers: Host is the domain name and Accept_- Language is the language to use, in this case American English. There are many HTTP headers available. HTTP messages also have an optional third section, known as the body. However we only see a body message with HTTP responses containing data. For simplicity, let’s assume that the Google homepage only contained the HTML “Hello, World!” This is what the HTTP response message from a Google server might look like. Diagram HTTP/1.1 200 OK Date: Wed, 28 Oct 2019 23:26:07 GMT Server: gws Accept-Ranges: bytes Content-Length: 13 Content-Type: text/html; charset=UTF-8 Hello, world! The top line is the response line and it specifies that we are using HTTP/1.1. The status code 200 OK indicates the request by the client was successful (more on status codes shortly).
📄 Page
20
Chapter 1: Web APIs 13 The next eight lines are HTTP headers. And finally after a line break there is our actual body content of “Hello, world!”. Every HTTP message, whether a request or response, therefore has the following format: Diagram Response/request line Headers... (optional) Body Most web pages contain multiple resources that require multiple HTTP request/re- sponse cycles. If a webpage hadHTML, oneCSS file, and an image, three separate trips back-and-forth between the client and server would be required before the complete web page could be rendered in the browser. Status Codes Once yourweb browser has executed anHTTPRequest on aURL there is no guarantee things will actually work! Thus there is a quite lengthy list of HTTP Status Codes available to accompany each HTTP response. You can tell the general type of status code based on the following system: • 2xx Success - the action requested by the client was received, understood, and accepted • 3xx Redirection - the requested URL has moved • 4xx Client Error - there was an error, typically a bad URL request by the client • 5xx Server Error - the server failed to resolve a request
The above is a preview of the first 20 pages. Register to read the complete e-book.