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
BIRMINGHAM—MUMBAI Building Data Science Applications with FastAPI Copyright © 2023 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. 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: Ali Abidi Publishing Product Managers: Dhruv J. Kataria and Tejashwini Content Development Editor: Shreya Moharir Technical Editor: Devanshi Ayare Copy Editor: Safis Editing Project Coordinator: Farheen Fathima Proofreader: Safis Editing Indexer: Tejal Soni
Page
3
Production Designer: Jyoti Chauhan Marketing Coordinator: Vinishka Kalra First published: October 2021 Second published: July 2023 Production reference: 1140723 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul’s Square Birmingham B3 1RB ISBN 978-1-83763-274-9 www.packtpub.com
Page
4
This second edition has been in the making for almost a year. During that time, I was blessed with an extraordinary gift: the arrival of our baby boy, Arthur, who has brought immeasurable joy into our lives. I dedicate this book to him and my beloved wife, whose unwavering support has been a constant source of inspiration and encouragement throughout this journey. Contributors About the author François Voron graduated from the University of Saint-Étienne (France) and the University of Alicante (Spain) with a master’s degree in machine learning and data mining. A full stack web developer and a data scientist, François has a proven track record working in the SaaS industry, with a special focus on Python backends and REST APIs. He is also the creator and maintainer of FastAPI Users, the #1 authentication library for FastAPI, and is one of the top experts in the FastAPI community. About the reviewers Izabela dos Santos Guerreiro graduated in information technology management and systems analysis and development. A machine learning enthusiast, she is a postgraduate in artificial intelligence, machine learning, and data science. She is a software developer specialist and tech lead and has nine years of experience, always working with Python. She was introduced to FastAPI about three years ago and became an enthusiast of the framework, collaborating on the translation of the documentation into her native language, Portuguese. She has already organized PyLadies and Django Girls events. Prajjwal Nijhara is an upcoming PhD computer scholar at IIT Jodhpur. With a passion for technology and research, Prajjwal has embarked on an academic journey to advance his expertise in computer science. Prior to this, Prajjwal gained industry experience as a software developer intern at Spiti
Page
5
and DeepSource, where he contributed to software development projects. Additionally, he served as a TGT guest faculty member at Pragyan Sthali School, imparting his knowledge and inspiring students in these subjects. I am deeply grateful to my brother, Roopak, and his partner, Chandrapurima, for their unwavering support. My heartfelt thanks also go to my parents, Subhash and Versha, who have been my rock throughout. Their love and guidance made the book review process smooth. I am truly blessed to have such incredible family members who believe in me and inspire me to pursue my aspirations. Akshat Gurnani is a highly qualified individual with a background in the field of computer science and machine learning. He has a master’s degree in computer science and a deep understanding of various machine learning techniques and algorithms. He has experience working on various projects related to natural language processing, computer vision, and deep learning. He has also published several research papers in top-tier journals and conferences and has a proven track record in the field. He has a passion for keeping up to date with the latest developments in his fields and has a strong desire to continue learning and contributing to the field of artificial intelligence.
Page
6
Table of Contents Preface
Page
7
Part 1: Introduction to Python and FastAPI 1 Python Development Environment Setup Technical requirements Installing a Python distribution using pyenv Creating a Python virtual environment Installing Python packages with pip Installing the HTTPie command-line utility Summary 2 Python Programming Specificities Technical requirements Basics of Python programming Running Python scripts Indentation matters Working with built-in types Working with data structures – lists, tuples, dictionaries, and sets Performing Boolean logic and a few other operators
Page
8
Controlling the flow of a program Defining functions Writing and using packages and modules Operating over sequences – list comprehensions and generators List comprehensions Generators Writing object-oriented programs Defining a class Implementing magic methods Reusing logic and avoiding repetition with inheritance Type hinting and type checking with mypy Getting started Type data structures Type function signatures with Callable Any and cast Working with asynchronous I/O Summary 3 Developing a RESTful API with FastAPI Technical requirements Creating a first endpoint and running it locally Handling request parameters
Page
9
Path parameters Query parameters The request body Form data and file uploads Headers and cookies The request object Customizing the response Path operation parameters The response parameter Raising HTTP errors Building a custom response Structuring a bigger project with multiple routers Summary 4 Managing Pydantic Data Models in FastAPI Technical requirements Defining models and their field types with Pydantic Standard field types Optional fields and default values Validating email addresses and URLs with Pydantic types Creating model variations with class inheritance Adding custom data validation with Pydantic
Page
10
Applying validation at the field level Applying validation at the object level Applying validation before Pydantic parsing Working with Pydantic objects Converting an object into a dictionary Creating an instance from a sub-class object Updating an instance partially Summary 5 Dependency Injection in FastAPI Technical requirements What is dependency injection? Creating and using a function dependency Getting an object or raising a 404 error Creating and using a parameterized dependency with a class Using class methods as dependencies Using dependencies at the path, router, and global level Using a dependency on a path decorator Using a dependency on a whole router Using a dependency on a whole application Summary
Page
11
Part 2: Building and Deploying a Complete Web Backend with FastAPI 6 Databases and Asynchronous ORMs Technical requirements An overview of relational and NoSQL databases Relational databases NoSQL databases Which one should you choose? Communicating with a SQL database with SQLAlchemy ORM Creating ORM models Defining Pydantic models Connecting to a database Creating objects Getting and filtering objects Updating and deleting objects Adding relationships Setting up a database migration system with Alembic Communicating with a MongoDB database using Motor Creating models that are compatible with MongoDB ID Connecting to a database
Page
12
Inserting documents Getting documents Updating and deleting documents Nesting documents Summary 7 Managing Authentication and Security in FastAPI Technical requirements Security dependencies in FastAPI Storing a user and their password securely in a database Creating models Hashing passwords Implementing registration routes Retrieving a user and generating an access token Implementing a database access token Implementing a login endpoint Securing endpoints with access tokens Configuring CORS and protecting against CSRF attacks Understanding CORS and configuring it in FastAPI Implementing double-submit cookies to prevent CSRF attacks Summary
Page
13
8 Defining WebSockets for Two-Way Interactive Communication in FastAPI Technical requirements Understanding the principles of two-way communication with WebSockets Creating a WebSocket with FastAPI Handling concurrency Using dependencies Handling multiple WebSocket connections and broadcasting messages Summary 9 Testing an API Asynchronously with pytest and HTTPX Technical requirements An introduction to unit testing with pytest Generating tests with parametrize Reusing test logic by creating fixtures Setting up testing tools for FastAPI with HTTPX Writing tests for REST API endpoints Writing tests for POST endpoints Testing with a database
Page
14
Writing tests for WebSocket endpoints Summary 10 Deploying a FastAPI Project Technical requirements Setting and using environment variables Using a .env file Managing Python dependencies Adding Gunicorn as a server process for deployment Deploying a FastAPI application on a serverless platform Adding database servers Deploying a FastAPI application with Docker Writing a Dockerfile Adding a prestart script Building a Docker image Running a Docker image locally Deploying a Docker image Deploying a FastAPI application on a traditional server Summary
Page
15
Part 3: Building Resilient and Distributed Data Science Systems with FastAPI 11 Introduction to Data Science in Python Technical requirements What is machine learning? Supervised versus unsupervised learning Model validation Manipulating arrays with NumPy and pandas Getting started with NumPy Manipulating arrays with NumPy – computation, aggregations, and comparisons Getting started with pandas Training models with scikit-learn Training models and predicting Chaining preprocessors and estimators with pipelines Validating the model with cross-validation Summary 12
Page
16
Creating an Efficient Prediction API Endpoint with FastAPI Technical requirements Persisting a trained model with Joblib Dumping a trained model Loading a dumped model Implementing an efficient prediction endpoint Caching results with Joblib Choosing between standard or async functions Summary 13 Implementing a Real-Time Object Detection System Using WebSockets with FastAPI Technical requirements Using a computer vision model with Hugging Face Implementing a REST endpoint to perform object detection on a single image Implementing a WebSocket to perform object detection on a stream of images Sending a stream of images from the browser in a WebSocket Showing the object detection results in the browser Summary 14
Page
17
Creating a Distributed Text-to-Image AI System Using the Stable Diffusion Model Technical requirements Generating images from text prompts with Stable Diffusion Implementing the model in a Python script Executing the Python script Creating a Dramatiq worker and defining an image-generation task Implementing a worker Implementing the REST API Storing results in a database and object storage Sharing data between the worker and the API Storing and serving files in object storage Summary 15 Monitoring the Health and Performance of a Data Science System Technical requirements Configuring and using a logging facility with Loguru Understanding log levels Adding logs with Loguru Understanding and configuring sinks
Page
18
Structuring logs and adding context Configuring Loguru as the central logger Adding Prometheus metrics Understanding Prometheus and the different metrics Measuring and exposing metrics Adding Prometheus metrics to FastAPI Adding Prometheus metrics to Dramatiq Monitoring metrics in Grafana Configuring Grafana to collect metrics Visualizing metrics in Grafana Summary Index Other Books You May Enjoy
Page
19
Preface FastAPI is a web framework for building APIs with Python 3.6 and its later versions based on standard Python type hints. With this book, you’ll be able to create fast and reliable data science API backends using practical examples. This book starts with the basics of the FastAPI framework and associated modern Python programming concepts. You’ll then be taken through all the aspects of the framework, including its powerful dependency injection system and how you can use it to communicate with databases, implement authentication, and integrate machine learning models. Later, you will cover the best practices relating to testing and deployment to run a high-quality, robust application. You’ll also be introduced to the extensive ecosystem of Python data science packages. As you progress, you’ll learn how to build data science applications in Python using FastAPI. The book also demonstrates how to develop fast and efficient machine learning prediction backends. For this, you’ll be taken through two projects covering typical use cases of AI: real-time object detection and text-to-image generation. By the end of this FastAPI book, you’ll have not only learned how to implement Python in data science projects but also how to maintain and design them to meet high programming standards with the help of FastAPI.
Page
20
Who this book is for This book is for data scientists and software developers interested in gaining knowledge of FastAPI and its ecosystem to build data science applications. Basic knowledge of data science and machine learning concepts and how to apply them in Python is recommended.
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A practical, project-driven guide to building production-grade data science APIs with FastAPI, covering everything from Python environment setup to deploying machine learning models for real-time object detection and text-to-image generation. Best suited for Python developers who want to bridge the gap between data science experimentation and robust, maintainable web backends.
【Book Arc】
- **Opening (~0%–10%)**: Establishes the foundation by setting up a professional Python development environment (pyenv, virtual environments, pip, HTTPie) and reviewing modern Python concepts like type hints, generators, and async/await that FastAPI relies on.
- **Early (~10%–32%)**: Introduces the core FastAPI framework—routing, path/query parameters, request bodies, response models, and Pydantic data validation—building toward a complete RESTful API.
- **Middle (~32%–55%)**: Deepens the architecture with Pydantic model management (field validation, object conversion) and FastAPI's powerful dependency injection system, showing how to reuse logic across endpoints, routers, and entire applications.
- **Late (~55%–80%)**: Connects the API to persistent storage using SQLAlchemy ORM and Pydantic schemas, then covers authentication, security, and testing practices for robust applications.
- **Ending (~80%–100%)**: Applies everything to real-world AI projects—integrating machine learning models for real-time object detection and text-to-image generation—and covers deployment strategies to run these applications in production.
【Key Takeaways】
- **FastAPI's async foundation is its performance edge** (Early): Built on ASGI and Python's async/await paradigm, FastAPI handles concurrent requests efficiently—understanding coroutines and event loops is essential before writing endpoints.
- **Pydantic models are the backbone of data validation** (Early–Middle): Every request and response flows through Pydantic, which enforces type safety, handles serialization, and generates automatic OpenAPI documentation. Field-level and object-level validators let you enforce business rules declaratively.
- **Dependency injection is FastAPI's architectural superpower** (Middle): Dependencies wrap reusable logic—pagination, authentication, database sessions—and can be applied at the path, router, or application level. This keeps endpoint functions clean and testable.
- **Separate ORM models from Pydantic schemas** (Late): Database communication uses SQLAlchemy models, while data validation and serialization use Pydantic schemas. The `orm_mode` config bridges the two, enabling seamless conversion between database rows and API responses.
- **Environment isolation prevents dependency conflicts** (Opening): Using pyenv and virtual environments is not optional—it's a professional necessity when juggling multiple projects with different Python versions and library requirements.
- **Real-world AI integration requires careful model serving** (Ending): The book demonstrates loading and serving ML models (object detection, text-to-image) through FastAPI endpoints, showing how to bridge the data science and web development worlds.
- **Testing and deployment are first-class concerns** (Late): The book emphasizes writing tests for endpoints and dependencies, and covers deployment strategies to ensure applications run reliably in production.
【Reading Tips】
- **Skim Chapter 1 if you're already comfortable with pyenv and virtual environments**—but don't skip the async/await section in Chapter 2, as it's foundational for everything that follows.
- **Deep-read the dependency injection chapter (Chapter 5)**: This is where FastAPI's design philosophy clicks, and mastering it will dramatically improve your application architecture.
- **Work through the two AI projects at the end hands-on**: They tie together every concept from the book and reveal practical challenges (model loading, inference latency, request handling) that theory alone won't teach.
- **Keep the Pydantic chapter bookmarked**: You'll return to it constantly as you define schemas for new endpoints and debug validation errors.
- **Don't rush the database chapter**: The ORM/schema separation pattern is easy to misunderstand but critical for maintainable code.
【Coverage Limits】
This guide is based on stratified excerpts covering the book's structure and key topics; specific code examples, chapter numbering details, and the full depth of the AI project implementations are not fully represented in the available excerpts.
Passage locations
Page 19
I: real-time object detection and text-to-image generation. By the end of this FastAPI book, you’ll have not only learned how to implement Python in data sci...
View in text
Excerpt 2
. However, for more complex hierarchies, the resolution may not be so obvious: this is the purpose of the Method Resolution Order (MRO) algorithm. We won’t g...
View in text
Excerpt 3
ng/Building-Data-Science-Applications- with-FastAPI-Second- In Chapter 3, Developing a RESTful API with FastAPI, you learned the basics of defining a data mo...
View in text
Excerpt 4
o secure your API, which we’ll cover in Chapter 7, Managing Authentication and Security in FastAPI. Using a dependency on a path decorator Relational databas...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay