Statistics
13
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-20
Support
Share

AuthorBill Lubanovic

FastAPI is a young yet solid framework that takes advantage of newer Python features in a clean design. As its name implies, FastAPI is indeed fast, rivaling similar frameworks in languages such as Golang. With this practical book, developers familiar with Python will learn how FastAPI lets you accomplish more in less time with less code. Author Bill Lubanovic covers the nuts and bolts of FastAPI development with how-to guides on various topics such as forms, database access, graphics, maps, and more that will take you beyond the basics. This book also includes how-to guides that will get you up to speed on RESTful APIs, data validation, authorization, and performance. With its similarities to frameworks like Flask and Django, you'll find it easy to get started with FastAPI. Through the course of this book, you will: Learn how to build web applications with FastAPI Understand the differences between FastAPI, Starlette, and pydantic Learn two...

Tags
No tags
Publisher: O'Reilly Media
Publish Year: 2023
Language: 英文
File Format: PDF
File Size: 10.1 MB
Support Statistics
¥.00 · 0times
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.

(This page has no text content)
FastAPI Modern Python Web Development Bill Lubanovic OceanofPDF.com
FastAPI by Bill Lubanovic Copyright © 2024 Bill Lubanovic. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (https://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or corporate@oreilly.com. Acquisitions Editor: Amanda Quinn Development Editor: Corbin Collins Production Editor: Kristen Brown Copyeditor: Sharon Wilkey Proofreader: Liz Wheeler Indexer: BIM Creatives, LLC Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Kate Dullea November 2023: First Edition Revision History for the First Edition
2023-11-06: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781098135508 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. FastAPI, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-098-13550-8 [LSI] OceanofPDF.com
Dedication To the loving memory of my wife, Mary, my parents, Bill and Tillie, and my friend, Rich. I miss you. OceanofPDF.com
Preface This is a pragmatic introduction to FastAPI—a modern Python web framework. It’s also a story of how, now and then, the bright and shiny objects that we stumble across can turn out to be very useful. A silver bullet is nice to have when you encounter a werewolf. (And you will encounter werewolves later in this book.) I started programming scientific applications in the mid-1970s. And after I first met Unix and C on a PDP-11 in 1977, I had a feeling that this Unix thing might catch on. In the ’80s and early ’90s, the internet was still noncommercial, but already a good source for free software and technical info. And when a web browser called Mosaic was distributed on the baby open internet in 1993, I had a feeling that this web thing might catch on. When I started my own web development company a few years later, my tools were the usual suspects at the time: PHP, HTML, and Perl. On a contract job a few years later, I finally experimented with Python and was surprised at how quickly I was able to access, manipulate, and display data. In my spare time over two weeks, I was able to replicate most of a C application that had taken four developers a year to write. Now I had a feeling that this Python thing might catch on. After that, most of my work involved Python and its web frameworks, mostly Flask and Django. I particularly liked the simplicity of Flask and preferred it for many jobs. But just a few years ago, I spied something glinting in the underbrush: a new Python web framework called FastAPI, written by Sebastián Ramírez. As I read his (excellent) documentation, I was impressed by the design and thought that had gone into it. In particular, his history page showed how much care he had taken evaluating alternatives. This was not an ego project
or a fun experiment, but a serious framework for real-world development. Now I had a feeling that this FastAPI thing might catch on. I wrote a biomedical API site with FastAPI, and it went so well that a team of us rewrote our old core API with FastAPI in the next year. This is still in production and has held up well. Our group learned the basics that you’ll read in this book, and all felt that we were writing better code, faster, with fewer bugs. And by the way, some of us had not written in Python before, and only I had used FastAPI. So when I had an opportunity to suggest a follow-up to my Introducing Python book to O’Reilly, FastAPI was at the top of my list. In my opinion, FastAPI will have at least the impact that Flask and Django have had, and maybe more. As I’ve mentioned, the FastAPI website itself provides world-class documentation, including many details on the usual web topics: databases, authentication, deployment, and so on. So why write a book? This book isn’t meant to be exhaustive because, well, that’s exhausting. It is meant to be useful—to help you quickly pick up the main ideas of FastAPI and apply them. I will point out various techniques that required some sleuthing and offer advice on day-to-day best practices. I start each chapter with a Preview of what’s coming. Next, I try not to forget what I just promised, offering details and random asides. Finally, there’s a brief digestible Review. As the saying goes, “These are the opinions on which my facts are based.” Your experience will be unique, but I hope that you will find enough of value here to become a more productive web developer. Conventions Used in This Book The following typographical conventions are used in this book: Italic
Indicates new terms, URLs, email addresses, filenames, and file extensions. Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords. Constant width bold Shows commands or other text that should be typed literally by the user. Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context. TIP This element signifies a tip or suggestion. NOTE This element signifies a general note. Using Code Examples Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/madscheme/fastapi. If you have a technical question or a problem using the code examples, please send email to support@oreilly.com.
This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but generally do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “FastAPI by Bill Lubanovic (O’Reilly). Copyright 2024 Bill Lubanovic, 978-1-098-13550-8.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. O’Reilly Online Learning NOTE For more than 40 years, O’Reilly Media has provided technology and business training, knowledge, and insight to help companies succeed. Our unique network of experts and innovators share their knowledge and expertise through books, articles, and our online learning platform. O’Reilly’s online learning platform gives you on-demand access to live training courses, in-depth learning paths, interactive coding environments, and a vast collection of text and video from O’Reilly and 200+ other publishers. For more information, visit https://oreilly.com.
How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-889-8969 (in the United States or Canada) 707-829-7019 (international or local) 707-829-0104 (fax) support@oreilly.com https://www.oreilly.com/about/contact.html We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at https://oreil.ly/FastAPI. For news and information about our books and courses, visit https://oreilly.com. Find us on LinkedIn: https://linkedin.com/company/oreilly-media. Follow us on Twitter: https://twitter.com/oreillymedia. Watch us on YouTube: https://youtube.com/oreillymedia. Acknowledgments Thanks to many people, at many places, from whom I’ve learned so much: Serra High School
OceanofPDF.com The University of Pittsburgh The Chronobiology Laboratories, University of Minnesota Intran Crosfield-Dicomed Northwest Airlines Tela WAM!NET Mad Scheme SSESCO Intradyn Keep Thomson Reuters Cray Penguin Computing Internet Archive CrowdStrike Flywheel
Part I. What’s New? The world has benefited greatly from the invention of the World Wide Web by Sir Tim Berners-Lee,1 and the Python programming language by Guido van Rossum. The only tiny problem is that a nameless computer book publisher often puts spiders and snakes on its relevant web and Python covers. If only the web had been named the World Wide Woof (cross-threads in weaving, also called weft), and Python were Pooch, this book might have had a cover like Figure I-1.
Figure I-1. FastAPI: Modern Pooch Woof Development But I digress.2 This book is about the following:
The web An especially productive technology, how it has changed, and how to develop software for it now Python An especially productive web development language FastAPI An especially productive Python web framework The two chapters in this first part discuss emerging topics in the web and in Python: services and APIs; concurrency; layered architectures; and big, big data. Part II is a high-level tour of FastAPI, a fresh Python web framework that has good answers to the questions posed in Part I. Part III rummages deeper through the FastAPI toolbox, including tips learned during production development. Finally, Part IV provides a gallery of FastAPI web examples. They use a common data source—imaginary creatures—that may be a little more interesting and cohesive than the usual random expositions. These should give you a starting point for particular applications. 1 I actually shook his hand once. I didn’t wash mine for a month, but I’ll bet he did right away. 2 Not for the last time. OceanofPDF.com
Chapter 1. The Modern Web The Web as I envisaged it, we have not seen it yet. The future is still so much bigger than the past. —Tim Berners-Lee Preview Once upon a time, the web was small and simple. Developers had such fun throwing PHP, HTML, and MySQL calls into single files and proudly telling everyone to check out their website. But the web grew over time to zillions, nay, squillions of pages—and the early playground became a metaverse of theme parks. In this chapter, I’ll point out some areas that have become ever more relevant to the modern web: Services and APIs Concurrency Layers Data The next chapter will show what Python offers in these areas. After that, we’ll dive into the FastAPI web framework and see what it has to offer. Services and APIs The web is a great connecting fabric. Although much activity still occurs on the content side—HTML, JavaScript, images, and so on—there’s an increasing emphasis on the application programming interfaces (APIs) that connect things.
Commonly, a web service handles low-level database access and middle- level business logic (often lumped together as a backend), while JavaScript or mobile apps provide a rich top-level frontend (interactive user interface). These fore and aft worlds have become more complex and divergent, usually requiring developers to specialize in one or the other. It’s harder to be a full stack developer than it used to be.1 These two worlds talk to each other using APIs. In the modern web, API design is as important as the design of websites themselves. An API is a contract, similar to a database schema. Defining and modifying APIs is now a major job. Kinds of APIs Each API defines the following: Protocol The control structure Format The content structure Multiple API methods have developed as technology has evolved from isolated machines, to multitasking systems, to networked servers. You’ll probably run across one or more of these at some point, so the following is a brief summary before getting to HTTP and its friends, which are featured in this book: Before networking, an API usually meant a very close connection, like a function call to a library in the same language as your application— say, calculating a square root in a math library. Remote procedure calls (RPCs) were invented to call functions in other processes, on the same machine or others, as though they were in the calling application. A popular current example is gRPC.
Messaging sends small chunks of data in pipelines among processes. Messages may be verb-like commands or may just indicate noun-like events of interest. Current popular messaging solutions, which vary broadly from toolkits to full servers, include Apache Kafka, RabbitMQ, NATS, and ZeroMQ. Communication can follow different patterns: Request-response One: one, like a web browser calling a web server. Publish-subscribe, or pub-sub A publisher emits messages, and subscribers act on each according to some data in the message, like a subject. Queues Like pub-sub, but only one of a pool of subscribers grabs the message and acts on it. Any of these may be used alongside a web service—for example, performing a slow backend task like sending an email or creating a thumbnail image. HTTP Berners-Lee proposed three components for his World Wide Web: HTML A language for displaying data HTTP A client-server protocol URLs An addressing scheme for web resources
Although these seem obvious in retrospect, they turned out to be a ridiculously useful combination. As the web evolved, people experimented, and some ideas, like the IMG tag, survived the Darwinian struggle. And as needs became clearer, people got serious about defining standards. REST(ful) One chapter in Roy Fielding’s Ph.D. thesis defined Representational State Transfer (REST)—an architectural style for HTTP use.2 Although often referenced, it’s been largely misunderstood. A roughly shared adaptation has evolved and dominates the modern web. It’s called RESTful, with these characteristics: Uses HTTP and client-server protocol Stateless (each connection is independent) Cacheable Resource-based A resource is data that you can distinguish and perform operations on. A web service provides an endpoint—a distinct URL and HTTP verb (action) —for each feature that it wants to expose. An endpoint is also called a route, because it routes the URL to a function. Database users are familiar with the CRUD acronym of procedures: create, read, update, delete. The HTTP verbs are pretty CRUDdy: POST Create (write) PUT Modify completely (replace) PATCH
Modify partially (update) GET Um, get (read, retrieve) DELETE Uh, delete A client sends a request to a RESTful endpoint with data in one of the following areas of an HTTP message: Headers The URL string Query parameters Body values In turn, an HTTP response returns these: An integer status code indicating the following: 100s Info, keep going 200s Success 300s Redirection 400s Client error 500s
Server error Various headers A body, which may be empty, single, or chunked (in successive pieces) At least one status code is an Easter egg: 418 (I’m a teapot) is supposed to be returned by a web-connected teapot, if asked to brew coffee. You’ll find many websites and books on RESTful API design, all with useful rules of thumb. This book will dole some out on the way. JSON and API Data Formats Frontend applications can exchange plain ASCII text with backend web services, but how can you express data structures like lists of things? Just about when we really started to need it, along came JavaScript Object Notation (JSON)—another simple idea that solves an important problem and seems obvious with hindsight. Although the J stands for JavaScript, the syntax looks a lot like Python too. JSON has largely replaced older attempts like XML and SOAP. In the rest of this book, you’ll see that JSON is the default web service input and output format. JSON:API The combination of RESTful design and JSON data formats is common now. But some wiggle room still remains for ambiguity and nerd tussles. The recent JSON:API proposal aims to tighten specs a bit. This book will
The above is a preview of the first 20 pages. Register to read the complete e-book.