Statistics
12
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-03-24

AuthorGiunio De Luca

Enhance your web development skills, from setting up your environment and advanced integrations to building robust, high-traffic web applications with practical, scalable solutions Key Features: - Explore FastAPI in depth, from basic setup to advanced features such as custom middleware and WebSockets - Discover practical strategies to optimize app performance and handle high traffic - Implement SQL and NoSQL integration techniques for versatile data management in FastAPI applications

Tags
No tags
ISBN: 1805127853
Publisher: Packt Publishing
Publish Year: 2024
Language: 英文
Pages: 359
File Format: PDF
File Size: 7.3 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.

1 S T E D I T I O N Develop high-performance APIs and web applications with Python FastAPI Cookbook F a stA P I C o o kb o o k GIUNIO DE LUCA, PHD Foreword by Antonio Ferraro, MSC Computer Science, Business Owner GIUNIO DE LUCA, PHD • Explore advanced FastAPI functionalities such as dependency injection, custom middleware, and WebSockets • Discover various types of data storage for powerful app functionality with SQL and NoSQL • Implement testing and debugging practices for clean, robust code • Integrate authentication and authorization mechanisms to secure web apps • Acquire skills to seamlessly migrate existing applications to FastAPI • Write unit and integration tests, ensuring reliability and security for your apps • Deploy your FastAPI apps to production environments for real-world use WHAT YOU WILL LEARN FastAPI is a cutting-edge Python framework that is revolutionizing the way web apps and APIs are built. Known for its speed, simplicity, and scalability, FastAPI empowers developers to create high-performing applications with ease. This book will help you leverage FastAPI’s immense potential to handle high-traffic scenarios and integrate seamlessly with modern Python tools. The book begins by familiarizing you with the basics of setting up and configuring your FastAPI environment before moving on to the intricacies of building RESTful APIs, managing data with SQL and NoSQL databases, and handling authentication and authorization. After that you’ll focus on advanced topics such as custom middleware, WebSocket communication, and integration with various Python libraries. Each chapter is meticulously crafted with practical recipes, progressing from foundational concepts to advanced features and best practices. The concluding chapters show you how to optimize performance, implement rate limiting, and execute background tasks, empowering you to become a proficient FastAPI developer. By the end of this book, you’ll have gained the skills you need to migrate existing apps to FastAPI and be equipped to tackle any challenge in the modern web development landscape, ensuring your apps are not only functional but also efficient, secure, and scalable. 1 S T E D I T I O N FastAPI Cookbook www.packtpub.com Get a free PDF of this book packt.link/free-ebook/9781805127857
FastAPI Cookbook Develop high-performance APIs and web applications with Python Giunio De Luca
FastAPI Cookbook Copyright © 2024 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It’s important to note that the content itself has been crafted by the author and edited by a professional publishing team.  Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.  Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.  Group Product Manager: Kaustubh Manglurkar Publishing Product Manager: Bhavya Rao Book Project Manager: Arul Viveaun S Senior Editor: Nathanya Dias Technical Editor: Simran Ali Copy Editor: Safis Editing Indexer: Manju Arasan Production Designer: Jyoti Kadam DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey First published: August 2024 Production reference: 1040724 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul’s Square Birmingham B3 1RB, UK ISBN 978-1-80512-785-7 www.packtpub.com
To my dear nephew, Marco. You bring endless joy to our lives. I wish you a future filled with love, growth, and happiness. May you always find success and fulfillment in everything you do. – Giunio De Luca
Foreword Having worked alongside Giunio for over a year, I can confidently say that his expertise and passion for Python development are evident in every line of code he produces. I affirm this with no shadow of a doubt, as I am a developer with over 30 years of experience across several countries and prominent industries, including Microsoft, NATO, and IBM. We naturally became friends due to our mutual respect and shared interests, both professional and personal. Giunio stood out in our team at Coreso, one of the European Regional Coordination Centers for high-voltage electricity flows. He has an impressive academic background coupled with extensive international experience. What truly sets him apart, however, is his deep and thorough understanding of Python and FastAPI. Giunio’s code is not only functional but also exceptionally clean and clear—a hallmark of a skilled developer, or in other words, a subject matter expert. Beyond his technical prowess, Giunio possesses a quality that I find equally important: an open mind. He readily embraces new challenges, tackling them with both enthusiasm and a solid foundation of knowledge, which he diligently builds and extends if he does not already possess it. I believe that he has brought these qualities to fruition in creating this book, pushing it beyond the scope of a typical cookbook. For instance, dealing with real-time communication and WebSockets is something rarely found in other cookbooks, and finding the right solution for your needs can consume a lot of valuable time searching online. This book promises to be a valuable resource for anyone seeking to become proficient in the use of FastAPI. Despite the excellent work the creators do with the product documentation, navigating it can easily lead to hours of frustration. Whether you’re a seasoned Python developer or just starting your journey, Giunio’s clear explanations and practical examples will guide you every step of the way. So, let Giunio be your expert guide to the power and efficiency of FastAPI! Antonio Ferraro MSC Computer Science, Business Owner
Contributors About the author Giunio De Luca is a software engineer with over 10 years of experience in fields such as physics, sports, and administration. He graduated in industrial engineering from the University of Basilicata and holds a PhD in numerical simulations from Paris-Saclay University. His work spans developing advanced algorithms, creating sports analytics applications, and improving administrative processes. As an independent consultant, he collaborates with research labs, government agencies, and start-ups across Europe. He also supports coding education in schools and universities through workshops, lectures, and mentorship programs, inspiring the next generation of software engineers with his expertise and dedication. With heartfelt gratitude, I thank my family and my loved ones for their continuous encouragement. I am also thankful to all my employers who have believed in my expertise, and my current clients and colleagues who keep trusting my work and providing me with valuable opportunities for professional growth.
About the reviewer Adarsh Divakaran is an experienced backend developer with expertise in architecting, building, and deploying APIs, primarily using Python. He is the co-founder of Digievo Labs, a global technology firm. He loves reading all sorts of Python content and runs a newsletter, Python in the Wild, showcasing Python concepts and examples from open source projects. Adarsh also speaks at global Python conferences, including PyCascades, EuroPython, and FlaskCon.
Preface xv 1 First Steps with FastAPI 1 Technical requirements 2 Setting up your development environment 2 Getting ready 3 How to do it... 4 Creating a new FastAPI project 6 Getting ready 6 How to do it... 6 There’s more... 8 See also 8 Understanding FastAPI basics 8 How to do it… 9 See also 11 Defining your first API endpoint 12 Getting ready 12 How to do it... 12 How it works… 13 Working with path and query parameters 13 Getting ready 14 How to do it… 14 How it works… 15 See also 15 Defining and using request and response models 15 Getting ready 16 How to do it... 16 See also 18 Handling errors and exceptions 19 How to do it… 19 There’s more… 20 See also 22 2 Working with Data 23 Technical requirements 24 Setting up SQL databases 25 Getting ready 25 How to do it… 25 Table of Contents
Table of Contentsviii Establishing a database connection 27 See also 28 Understanding CRUD operations with SQLAlchemy 28 Getting ready 29 How to do it… 29 See also 32 Integrating MongoDB for NoSQL data storage 32 Getting ready 32 How to do it… 33 See also 35 Working with data validation and serialization 36 Getting ready 36 How to do it… 36 Serialization and deserialization concepts 37 Advanced validation techniques 38 See also 39 Working with file uploads and downloads 39 Getting ready 39 How to do it… 39 Implementing file uploads 40 Managing file downloads and storage 41 See also 42 Handling asynchronous data operations 42 Getting ready 42 How to do it… 42 There’s more… 46 See also 46 Securing sensitive data and best practices 47 Getting ready 47 How to do it… 48 There’s more… 48 3 Building RESTful APIs with FastAPI 51 Technical requirements 52 Creating CRUD operations 52 How to do it… 53 How it works... 56 Creating RESTful Endpoints 57 Getting ready… 57 How to do it… 57 Testing your RESTful API 59 Getting ready… 60 How to do it... 61 See also 64 Handling complex queries and filtering 64 Getting ready… 64 How to do it... 64 Versioning your API 66 Getting ready… 66 How to do it... 66 There’s more… 68 See also 69 Securing your API with OAuth2 69 Getting ready… 69 How to do it… 69 There’s more… 73
Table of Contents ix See also 73 Documenting your API with Swagger and Redoc 74 Getting ready… 74 How to do it... 74 See also 75 4 Authentication and Authorization 77 Technical requirements 78 Setting up user registration 78 Getting ready 78 How to do it… 79 How it works... 82 See also 83 Working with OAuth2 and JWT for authentication 83 Getting ready 83 How to do it... 83 How it works… 87 See also 88 Setting up RBAC 88 Getting ready 88 How to do it... 90 There’s more… 93 Using third-party authentication 94 Getting ready 94 How to do it... 95 How it works… 98 See also 99 Implementing MFA 99 Getting ready 100 How to do it... 100 See also 103 Handling API key authentication 103 Getting ready 104 How to do it... 104 There’s more… 105 Handling session cookies and logout functionality 105 Getting ready 106 How to do it... 106 There’s more… 107 See also 108 5 Testing and Debugging FastAPI Applications 109 Technical requirements 110 Setting up testing environments 110 Getting ready 110 How to do it... 111 See also 112 Writing and running unit tests 113 Getting ready 113 How to do it… 113 See also 114 Testing API Endpoints 114
Table of Contentsx Getting ready 114 How to do it… 118 See also 120 Running tests techniques 120 Getting ready 120 How to do it... 120 Check test coverage 122 See also 122 Handling logging messages 123 Getting ready 123 How to do it... 123 There’s more 125 See also 126 Debugging techniques 126 Getting ready 126 How to do it... 126 Debugging with PDB 127 Debugging with VS Code 128 Debugging with PyCharm 129 See also 130 Performance testing for high traffic applications 131 Getting ready 131 How to do it... 131 See also 133 6 Integrating FastAPI with SQL Databases 135 Technical requirements 136 Setting up SQLAlchemy 136 Getting ready 136 How to do it... 137 How it works… 139 See also 140 Implementing CRUD operations 141 Getting ready 141 How to do it… 141 How it works… 144 Working with migrations 144 Getting ready 145 How to do it… 145 How it works… 146 See also 147 Handling relationships in SQL databases 147 Getting ready 147 How to do it… 147 See also 152 Optimizing SQL queries for performance 152 Getting ready 152 How to do it… 153 There’s more… 156 Securing sensitive data in SQL databases 156 Getting ready 156 How to do it… 157 See also 160 Handling transactions and concurrency 160 Getting ready 160 How to do it… 160 There’s more… 163 See also 165
Table of Contents xi 7 Integrating FastAPI with NoSQL Databases 167 Technical requirements 168 Setting up MongoDB with FastAPI 168 Getting ready 168 How to do it… 169 See also 171 CRUD operations in MongoDB 171 Getting ready 171 How to do it… 171 See also 175 Handling relationships in NoSQL databases 175 Getting ready 176 How to do it… 176 See also 179 Working with indexes in MongoDB 179 Getting ready 179 How to do it… 179 How it works… 180 There’s more… 181 See also 183 Exposing sensitive data from NoSQL databases 183 Getting ready 183 How to do it… 184 There’s more… 188 See also 189 Integrating FastAPI with Elasticsearch 189 Getting ready 189 How to do it… 190 See also 196 Using Redis for caching in FastAPI 197 Getting ready 197 How to do it… 198 There’s more… 200 See also 200 8 Advanced Features and Best Practices 201 Technical requirements 202 Implementing dependency injection 202 Getting ready 202 How to do it… 203 How it works… 206 There’s more… 206 See also 209 Creating custom middleware 209 Getting ready… 209 How to do it… 209 How it works… 211 See also 211 Internationalization and localization 211 Getting ready 212 How to do it… 212
Table of Contentsxii See also 216 Optimizing application performance 216 Getting ready 216 How to do it… 217 There’s more... 218 See also 219 Implementing rate limiting 219 Getting ready 220 How to do it… 220 There's more... 221 See also 222 Implementing background tasks 222 Getting ready 223 How to do it… 223 How it works… 224 See also 224 9 Working with WebSocket 225 Technical requirements 225 Setting up WebSockets in FastAPI 226 Getting ready 226 How to do it… 227 How it works… 227 See also 228 Sending and receiving messages over WebSockets 228 Getting ready 228 How to do it… 228 See also 230 Handling WebSocket connections and disconnections 230 Getting ready 230 How to do it… 230 Handling WebSocket errors and exceptions 232 Getting ready 232 How to do it… 232 See also 234 Implementing chat functionality with WebSockets 235 Getting ready 235 How to do it… 236 How it works… 239 See also 240 Optimizing WebSocket performance 240 Getting ready 240 How to do it… 241 There’s more… 243 See also 244 Securing WebSocket connections with OAuth2 244 Getting ready 244 How to do it… 245 See also 248
Table of Contents xiii 10 Integrating FastAPI with other Python Libraries 249 Technical requirements 250 Integrating FastAPI with gRPC 250 Getting ready 250 How to do it… 253 There’s more… 254 See also 255 Connecting FastAPI with GraphQL 255 Getting ready 255 How to do it… 256 See also 258 Using ML models with Joblib 259 Getting ready 259 How to do it… 260 See also 262 Integrating FastAPI with Cohere 262 Getting ready 263 How to do it… 264 See also 267 Integrating FastAPI with LangChain 267 Getting ready 267 How to do it… 268 See also 275 11 Middleware and Webhooks 277 Technical requirements 278 Creating custom ASGI middleware 278 Getting ready 278 How to do it… 279 How it works… 280 There’s more… 281 See also 282 Developing middleware for request modification 282 Getting ready 283 How to do it… 283 See also 286 Developing middleware for response modification 286 Getting ready 286 How to do it… 286 See also 289 Handling CORS with middleware 289 Getting ready 289 How to do it… 290 See also 290 Restricting incoming requests from hosts 291 Getting ready 291 How to do it… 291 See also 292 Implementing webhooks 292 Getting ready 293 How to do it… 293 How it works… 298 There’s more… 299 See also 299
Table of Contentsxiv 12 Deploying and Managing FastAPI Applications 301 Technical requirements 302 Running the server with the FastAPI CLI 302 Getting ready 302 How to do it… 303 There’s more… 304 See also 305 Enabling HTTPS on FastAPI applications 305 Getting ready 305 How to do it… 306 There’s more… 307 See also 308 Running FastAPI applications in Docker containers 308 Getting ready 308 How to do it… 309 See also 311 Running the server across multiple workers 311 Getting ready 311 How to do it… 311 There’s more… 313 See also 313 Deploying your FastAPI application on the cloud 314 Getting started 314 How to do it… 314 There’s more… 316 See also 316 Shipping FastAPI applications with Hatch 317 Getting ready 317 How to do it… 318 There’s more… 321 See also 322 Index 323 Other Books You May Enjoy 332
Preface FastAPI Cookbook is a vital resource for Python developers who want to master the FastAPI framework to build APIs. Created by Sebastián Ramírez Montaño, FastAPI was first released in December 2018. It quickly gained popularity and became one of the most widely used Python frameworks for building APIs. The book starts by introducing FastAPI, showing its advantages, and it will help you set up your development environment. It then moves on to data handling, showing database integration and create, read, update and delete (CRUD) operations, to help you manage data effectively within your APIs. As the book progresses, it explores how to create RESTful APIs, covering advanced topics such as complex queries, versioning, and extensive documentation. Security is also important, and the book has a chapter on implementing authentication mechanisms such as OAuth2 and JWT tokens to secure FastAPI applications. Testing is an essential part of development, and the book offers strategies to ensure the quality and reliability of FastAPI applications. Deployment strategies are discussed, highlighting best practices for production environments. For applications with high traffic, the book examines scaling techniques to improve performance. Extending FastAPI’s functionality is possible through middleware, and the book also demonstrates how to boost FastAPI’s capabilities by integrating it with other Python tools and frameworks to accommodate machine learning models and expose LLM RAG applications. Real-time communication is handled with a chapter on WebSockets, and advanced data handling techniques are provided to manage large datasets and file management. The book ends with a focus on serving real-world traffic with FastAPI, stressing deployment strategies and packaging shipping. Each chapter is carefully designed to build your expertise, making the FastAPI Cookbook a valuable guide for professional-grade API development. Who this book is for The book is tailored for intermediate to advanced Python developers who have a foundational understanding of web development concepts. It’s particularly beneficial for those seeking to build efficient, scalable APIs with the modern FastAPI framework. The book is a valuable resource for developers looking to enhance their API development skills and apply practical solutions to real- world programming challenges. Whether you’re looking to secure APIs, manage data effectively, or optimize performance, this book provides the knowledge and hands-on examples to elevate your expertise in FastAPI.
Prefacexvi What this book covers Chapter 1, First Steps with FastAPI, serves as an introduction to the framework, emphasizing its speed, ease of use, and comprehensive documentation. This chapter is the gateway for you to set up your development environment, create your first FastAPI project, and explore its fundamental concepts. Chapter 2, Working with Data, is dedicated to mastering the critical aspect of data handling in web applications. It covers the intricacies of integrating, managing, and optimizing data storage using both SQL and NoSQL databases. Chapter 3, Building RESTful APIs with FastAPI, dives into the essentials of constructing RESTful APIs, which are fundamental to web services, enabling applications to communicate and exchange data efficiently. Chapter 4, Authentication and Authorization, delves into the critical realms of securing your web applications against unauthorized access. It covers the basics of user registration and authentication, the integration of OAuth2 protocols with JWT for enhanced security, and the creation of essential components for an API. Chapter 5, Testing and Debugging FastAPI Applications, pivots toward a crucial aspect of software development that ensures the reliability, robustness, and quality of your applications – testing and debugging. Chapter 6, Integrating FastAPI with SQL Databases, embarks on a journey to harness the full potential of SQL databases within FastAPI applications. It is meticulously designed to guide you through leveraging SQLAlchemy, a powerful SQL toolkit and Object-Relational Mapper (ORM) for Python. Chapter 7, Integrating FastAPI with NoSQL Databases, explores the integration of FastAPI with NoSQL databases by guiding you through the process of setting up and using MongoDB, a popular NoSQL database, with FastAPI. It covers CRUD operations, working with indexes for performance optimization, and handling relationships in NoSQL databases. Additionally, the chapter discusses integrating FastAPI with Elasticsearch for powerful search capabilities and implementing caching using Redis. Chapter 8, Advanced Features and Best Practices, explores advanced techniques and best practices to optimize the functionality, performance, and scalability of FastAPI applications. It covers essential topics such as dependency injection, custom middleware, internationalization, performance optimization, rate limiting, and background task execution. Chapter 9, Working with WebSockets, is a comprehensive guide to implementing real-time communication features in FastAPI applications using WebSockets. It covers setting up WebSocket connections, sending and receiving messages, handling connections and disconnections, error handling, and implementing chat functionality. Chapter 10, Integrating FastAPI with other Python Libraries, deep dives into the potential of FastAPI when coupled with external libraries, enhancing its capabilities beyond its core features. It provides a recipe-based approach to integrating FastAPI with various technologies, such as Cohere and LangChain, to build LLM RAG applications.
Preface xvii Chapter 11, Middleware and Webhooks, delves into the advanced and crucial aspects of middleware and Webhooks in FastAPI. Middleware allows you to process requests and responses globally, while Webhooks enable your FastAPI application to communicate with other services by sending real-time data updates. Chapter 12, Deploying and Managing FastAPI Applications, covers the knowledge and tools needed to deploy FastAPI applications seamlessly, leveraging various technologies and best practices. You will learn how to utilize the FastAPI CLI to run your server efficiently, enable HTTPS to secure your applications, and containerize your FastAPI projects with Docker. To get the most out of this book You should have a fundamental understanding of Python programming, as the book assumes familiarity with Python syntax and concepts. Additionally, knowledge of web development principles, including HTTP, RESTful APIs, and JSON, will be beneficial. Familiarity with SQL and NoSQL databases, as well as experience with version control systems such as Git, will help you to fully grasp the content. Software/hardware covered in the book OS requirements Python 3.9 or higher Windows, macOS, or Linux (any) If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code. Download the example code files You can download the example code files for this book from GitHub at https://github.com/ PacktPublishing/FastAPI-Cookbook. If there’s an update to the code, it will be updated on the existing GitHub repository. We also have other code bundles from our rich catalog of books and videos available at https:// github.com/PacktPublishing/. Check them out! Conventions used There are a number of text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Also, you will find only the messages from our logger_client in a newly created app.log file automatically created by the application.”
Prefacexviii A block of code is set as follows: from locust import HttpUser, task class ProtoappUser(HttpUser): host = "http://localhost:8000" @task def hello_world(self): self.client.get("/home") When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: from pydantic import BaseModel, Field class Book(BaseModel): title: str = Field(..., min_length=1, max_length=100) author: str = Field(..., min_length=1, max_length=50) year: int = Field(..., gt=1900, lt=2100) Any command-line input or output is written as follows: $ pytest –-cov protoapp tests Throughout this book, we will generally use Unix-like terminal commands. This might lead to compatibility issues with Windows for commands that run on multiple lines. If you are using a Windows terminal, consider adapting the newline character \ as follows: $ python -m grpc_tools.protoc \ --proto_path=. ./grpcserver.proto \ --python_out=. \ --grpc_python_out=. Here is the same line in CMD: $ python -m grpc_tools.protoc ^ --proto_path=. ./grpcserver.proto ^ --python_out=. ^ --grpc_python_out=.
Preface xix Here is the line in Powershell: $ python -m grpc_tools.protoc ` --proto_path=. ./grpcserver.proto ` --python_out=. ` --grpc_python_out=. Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “This limit can be adjusted in the settings (Settings | Advanced Settings | Run/Debug | Temporary configurations limit).” Tips or important notes Appear like this. Sections In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There’s more..., and See also). To give clear instructions on how to complete a recipe, use these sections as follows. Getting ready This section tells you what to expect in the recipe and describes how to set up any software or preliminary settings required for it. How to do it… This section contains the steps required to follow the recipe. How it works… This section usually consists of a detailed explanation of what happened in the previous section. There’s more… This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe. See also This section provides helpful links to other useful information for the recipe.