Building Data Science Applications with FastAPI - Second Edition

This document was uploaded by one of our users. The uploader already confirmed that they had the permission to publish it. If you are author/publisher or own the copyright of this documents, please report to us by using this DMCA report form.

Simply click on the Download Book button.

Yes, Book downloads on Ebookily are 100% Free.

Sometimes the book is free on Amazon As well, so go ahead and hit "Search on Amazon"

Learn all the features and best practices of FastAPI to build, deploy, and monitor powerful data science and AI apps, like object detection or image generation. Purchase of the print or Kindle book includes a free PDF eBook Key Features Uncover the secrets of FastAPI, including async I/O, type hinting, and dependency injection Learn to add authentication, authorization, and interaction with databases in a FastAPI backend Develop real-world projects using pre-trained AI models Book Description Building Data Science Applications with FastAPI is the go-to resource for creating efficient and dependable data science API backends. This second edition incorporates the latest Python and FastAPI advancements, along with two new AI projects – a real-time object detection system and a text-to-image generation platform using Stable Diffusion. The book starts with the basics of FastAPI and modern Python programming. You'll grasp FastAPI's robust dependency injection system, which facilitates seamless database communication, authentication implementation, and ML model integration. As you progress, you'll learn testing and deployment best practices, guaranteeing high-quality, resilient applications. Throughout the book, you'll build data science applications using FastAPI with the help of projects covering common AI use cases, such as object detection and text-to-image generation. These hands-on experiences will deepen your understanding of using FastAPI in real-world scenarios. By the end of this book, you'll be well equipped to maintain, design, and monitor applications to meet the highest programming standards using FastAPI, empowering you to create fast and reliable data science API backends with ease while keeping up with the latest advancements. What you will learn Explore the basics of modern Python and async I/O programming Get to grips with basic and advanced concepts of the FastAPI framework Deploy a performant and reliable web backend for a data science application Integrate common Python data science libraries into a web backend Integrate an object detection algorithm into a FastAPI backend Build a distributed text-to-image AI system with Stable Diffusion Add metrics and logging and learn how to monitor them 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.

Author(s): François Voron
Edition: 2
Publisher: Packt Publishing
Year: 2023

Language: English
Pages: 422

Contributors
About the author
About the reviewers
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Share Your Thoughts
Download a free PDF copy of this book
Part 1: Introduction to Python and FastAPI
Chapter 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
Chapter 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
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
Chapter 3: Developing a RESTful API with FastAPI
Technical requirements
Creating a first endpoint and running it locally
Handling request parameters
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
Chapter 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
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
Chapter 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
Part 2: Building and Deploying a Complete Web Backend with FastAPI
Chapter 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
Inserting documents
Getting documents
Updating and deleting documents
Nesting documents
Summary
Chapter 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
Chapter 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
Chapter 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
Writing tests for WebSocket endpoints
Summary
Chapter 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
Part 3: Building Resilient and Distributed Data Science Systems with FastAPI
Chapter 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
Chapter 12: 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
Chapter 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
Chapter 14: 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
Chapter 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
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
Why subscribe?
Other Books You May Enjoy
Packt is searching for authors like you
Share Your Thoughts
Download a free PDF copy of this book