Reader small image

You're reading from  Building Data Science Applications with FastAPI - Second Edition

Product typeBook
Published inJul 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781837632749
Edition2nd Edition
Languages
Tools
Concepts
Right arrow
Author (1)
François Voron
François Voron
author image
François Voron

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.
Read more about François Voron

Right arrow

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.

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.

What this book covers

Chapter 1, Python Development Environment Setup, is aimed at setting up the development environment so that you can start working with Python and FastAPI. We’ll introduce the various tools that are commonly used in the Python community to ease development.

Chapter 2, Python Programming Specificities, introduces you to the specificities of programming in Python, specifically block indentation, control flow statements, exception handling, and the object-oriented paradigm. We’ll also cover features such as list comprehensions and generators. Finally, we’ll see how type hinting and asynchronous I/O work.

Chapter 3, Developing a RESTful API with FastAPI, covers the basics of the creation of a RESTful API with FastAPI: routing, parameters, request body validation, and response. We’ll also show how to properly structure a FastAPI project with dedicated modules and separate routers.

Chapter 4, Managing Pydantic Data Models in FastAPI, covers in more detail the definition of data models with Pydantic, the underlying data validation library used by FastAPI. We’ll explain how to implement variations of the same model without repeating ourselves, thanks to class inheritance. Finally, we’ll show how to implement custom data validation logic on those models.

Chapter 5, Dependency Injection in FastAPI, explains how dependency injection works and how we can define our own dependencies to reuse logic across different routers and endpoints.

Chapter 6, Databases and Asynchronous ORMs, demonstrates how we can set up a connection with a database to read and write data. We’ll cover how to use SQLAlchemy to work asynchronously with SQL databases and how they interact with the Pydantic model. Finally, we’ll also show you how to work with MongoDB, a NoSQL database.

Chapter 7, Managing Authentication and Security in FastAPI, shows us how to implement a basic authentication system to protect our API endpoints and return the relevant data for the authenticated user. We’ll also talk about the best practices around CORS and how to be safe from CSRF attacks.

Chapter 8, Defining WebSockets for Two-Way Interactive Communication in FastAPI, is aimed at understanding WebSockets and how to create them and handle the messages received with FastAPI.

Chapter 9, Testing an API Asynchronously with pytest and HTTPX, shows us how to write tests for our REST API endpoints.

Chapter 10, Deploying a FastAPI Project, covers the common configuration for running FastAPI applications smoothly in production. We’ll also explore several deployment options: PaaS platforms, Docker, and the traditional server setup.

Chapter 11, Introduction to Data Science in Python, gives a quick introduction to machine learning before moving on to two core libraries for data science in Python: NumPy and pandas. We’ll also show the basics of the scikit-learn library, a set of ready-to-use tools to perform machine learning tasks in Python.

Chapter 12, Creating an Efficient Prediction API Endpoint with FastAPI, shows how we can efficiently store a trained machine learning model using Joblib. Then, we’ll integrate it into a FastAPI backend, considering some technical details of FastAPI internals to achieve maximum performance. Finally, we’ll show a way to cache results using Joblib.

Chapter 13, Implementing a Real-Time Object Detection System Using WebSockets with FastAPI, implements a simple application to perform object detection in the browser, backed by a FastAPI WebSocket and a pre-trained computer vision model from the Hugging Face library.

Chapter 14, Creating a Distributed Text-to-Image AI System Using the Stable Diffusion Model, implements a system able to generate images from text prompts using the popular Stable Diffusion model. Since this task is a resource-intensive, slow process, we’ll see how to create a distributed system using worker queues that’ll stand behind our FastAPI backend and will perform the computations in the background.

Chapter 15, Monitoring the Health and Performance of a Data Science System, covers the extra mile so you are able to build robust, production-ready systems. One of the most important aspects to achieve this is to have all the data we need to ensure the system is operating correctly and detect as soon as possible when something goes wrong so we can take corrective actions. In this chapter, we’ll see how to set up a proper logging facility and how we can monitor the performance and health of our software in real time.

To get the most out of this book

In this book, we’ll mainly work with the Python programming language. The first chapter will explain how to set up a proper Python environment on your operating system. Some examples also involve running web pages with JavaScript, so you’ll need a modern browser such as Google Chrome or Mozilla Firefox.

In Chapter 14, we’ll run the Stable Diffusion model, which requires a powerful machine. We recommend a computer with 16 GB of RAM and a modern NVIDIA GPU to be able to generate good-looking images.

Software/hardware covered in the book

Operating system requirements

Python 3.10+

Windows, macOS, or Linux

Javascript

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Building-Data-Science-Applications-with-FastAPI-Second-Edition. If there’s an update to the code, it will be updated in the 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: “Obviously, if everything is okay, we get a Person instance and have access to the properly parsed fields.”

A block of code is set as follows:

from fastapi import FastAPIapp = FastAPI()
@app.get("/users/{type}/{id}")
async def get_user(type: str, id: int):
    return {"type": type, "id": id}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

class PostBase(BaseModel):    title: str
    content: str
    def excerpt(self) -> str:
        return f"{self.content[:140]}..."

Any command-line input or output is written as follows:

$ http http://localhost:8000/users/abcHTTP/1.1 422 Unprocessable Entity
content-length: 99
content-type: application/json
date: Thu, 10 Nov 2022 08:22:35 GMT
server: uvicorn

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packtpub.com with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Building Data Science Applications with FastAPI, Second Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

  1. Scan the QR code or visit the link below

https://packt.link/free-ebook/9781837632749

  1. Submit your proof of purchase
  2. That’s it! We’ll send your free PDF and other benefits to your email directly
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Building Data Science Applications with FastAPI - Second Edition
Published in: Jul 2023Publisher: PacktISBN-13: 9781837632749
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
François Voron

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.
Read more about François Voron