Building Data Science Applications with FastAPI - Second Edition [2 ed.] 9781837632749

Learn all the features and best practices of FastAPI to build, deploy, and monitor powerful data science and AI apps, li

126 45 6MB

English Pages 422 Year 2023

Report DMCA / Copyright

DOWNLOAD EPUB FILE

Table of contents :
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

Building Data Science Applications with FastAPI - Second Edition [2 ed.]
 9781837632749

  • 0 0 0
  • Like this paper and download? You can publish your own PDF file online for free in a few minutes! Sign Up
Recommend Papers