FastAPI Cookbook: Develop high-performance APIs and web applications with Python
By Giunio De Luca and Antonio Ferraro
()
Related to FastAPI Cookbook
Related ebooks
Mastering Django for Backend Development: A Practical Guide Rating: 0 out of 5 stars0 ratingsNext-Gen Backend Development: Mastering Python and Django Techniques Rating: 0 out of 5 stars0 ratingsPython APIs: From Concept to Implementation Rating: 5 out of 5 stars5/5Building the Future: Advanced Web Development Techniques with Flask and Python Rating: 0 out of 5 stars0 ratingsSpring Boot 3.0 Cookbook: Proven recipes for building modern and robust Java web applications with Spring Boot Rating: 0 out of 5 stars0 ratingsModern API Design: REST, GraphQL, and Beyond Rating: 0 out of 5 stars0 ratingsMinimal APIs in ASP.NET 9: Design, implement, and optimize robust APIs in C# with .NET 9 Rating: 0 out of 5 stars0 ratingsFull Stack Development Explained: From Frontend to Backend Rating: 0 out of 5 stars0 ratingsThe Supabase Handbook: Scalable Backend Solutions for Developers Rating: 0 out of 5 stars0 ratingsModern Full-Stack React Projects: Build, maintain, and deploy modern web apps using MongoDB, Express, React, and Node.js Rating: 0 out of 5 stars0 ratingsA Guide To All Programming and Coding Languages Rating: 0 out of 5 stars0 ratingsReact JS and Express Framework: A Comprehensive Guide Rating: 0 out of 5 stars0 ratingsLaravel 5.x Cookbook Rating: 0 out of 5 stars0 ratingsThe Mobile Web: Responsive design for a multi device world Rating: 0 out of 5 stars0 ratingsMessaging in Flutter Rating: 0 out of 5 stars0 ratingsDart By Example Rating: 0 out of 5 stars0 ratingsMastering Secure Java Applications: Navigating security in cloud and microservices for Java (English Edition) Rating: 0 out of 5 stars0 ratingsInstant HTML5 Geolocation How-To Rating: 0 out of 5 stars0 ratingsNoSQL Essentials: Navigating the World of Non-Relational Databases Rating: 0 out of 5 stars0 ratingsiOS 13 Programming for Beginners - Fourth Edition: Get started with building iOS apps with Swift 5 and Xcode 11, 4th Edition Rating: 0 out of 5 stars0 ratingsLearn Angular: Build a Todo App Rating: 0 out of 5 stars0 ratingsTwilio Best Practices Rating: 0 out of 5 stars0 ratingsMastering Postman: A Comprehensive Guide to Building End-to-End APIs with Testing, Integration and Automation Rating: 0 out of 5 stars0 ratingsNode.js Blueprints Rating: 0 out of 5 stars0 ratings
Internet & Web For You
Coding For Dummies Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 4 out of 5 stars4/5Canva Tips and Tricks Beyond The Limits Rating: 3 out of 5 stars3/5More Porn - Faster!: 50 Tips & Tools for Faster and More Efficient Porn Browsing Rating: 3 out of 5 stars3/5Notion for Beginners: Notion for Work, Play, and Productivity Rating: 4 out of 5 stars4/5How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Get Into UX: A foolproof guide to getting your first user experience job Rating: 4 out of 5 stars4/5UX/UI Design Playbook Rating: 4 out of 5 stars4/5Social Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5SEO For Dummies Rating: 4 out of 5 stars4/5The Complete Website Planning Guide Rating: 4 out of 5 stars4/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5Cybersecurity For Dummies Rating: 5 out of 5 stars5/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5Ready, Set, Brand!: The Canva for Work Quickstart Guide Rating: 5 out of 5 stars5/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5Content Chemistry: The Illustrated Handbook for Content Marketing Rating: 5 out of 5 stars5/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratings
Reviews for FastAPI Cookbook
0 ratings0 reviews
Book preview
FastAPI Cookbook - 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: 2040924
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.
Table of Contents
Preface
1
First Steps with FastAPI
Technical requirements
Setting up your development environment
Getting ready
How to do it...
Creating a new FastAPI project
Getting ready
How to do it...
There’s more...
See also
Understanding FastAPI basics
How to do it…
See also
Defining your first API endpoint
Getting ready
How to do it...
How it works…
Working with path and query parameters
Getting ready
How to do it…
How it works…
See also
Defining and using request and response models
Getting ready
How to do it...
See also
Handling errors and exceptions
How to do it…
There’s more…
See also
2
Working with Data
Technical requirements
Setting up SQL databases
Getting ready
How to do it…
Establishing a database connection
See also
Understanding CRUD operations with SQLAlchemy
Getting ready
How to do it…
See also
Integrating MongoDB for NoSQL data storage
Getting ready
How to do it…
See also
Working with data validation and serialization
Getting ready
How to do it…
Serialization and deserialization concepts
Advanced validation techniques
See also
Working with file uploads and downloads
Getting ready
How to do it…
Implementing file uploads
Managing file downloads and storage
See also
Handling asynchronous data operations
Getting ready
How to do it…
There’s more…
See also
Securing sensitive data and best practices
Getting ready
How to do it…
There’s more…
3
Building RESTful APIs with FastAPI
Technical requirements
Creating CRUD operations
How to do it…
How it works...
Creating RESTful Endpoints
Getting ready…
How to do it…
Testing your RESTful API
Getting ready…
How to do it...
See also
Handling complex queries and filtering
Getting ready…
How to do it...
Versioning your API
Getting ready…
How to do it...
There’s more…
See also
Securing your API with OAuth2
Getting ready…
How to do it…
There’s more…
See also
Documenting your API with Swagger and Redoc
Getting ready…
How to do it...
See also
4
Authentication and Authorization
Technical requirements
Setting up user registration
Getting ready
How to do it…
How it works...
See also
Working with OAuth2 and JWT for authentication
Getting ready
How to do it...
How it works…
See also
Setting up RBAC
Getting ready
How to do it...
There’s more…
Using third-party authentication
Getting ready
How to do it...
How it works…
See also
Implementing MFA
Getting ready
How to do it...
See also
Handling API key authentication
Getting ready
How to do it...
There’s more…
Handling session cookies and logout functionality
Getting ready
How to do it...
There’s more…
See also
5
Testing and Debugging FastAPI Applications
Technical requirements
Setting up testing environments
Getting ready
How to do it...
See also
Writing and running unit tests
Getting ready
How to do it…
See also
Testing API Endpoints
Getting ready
How to do it…
See also
Running tests techniques
Getting ready
How to do it...
Check test coverage
See also
Handling logging messages
Getting ready
How to do it...
There’s more
See also
Debugging techniques
Getting ready
How to do it...
Debugging with PDB
Debugging with VS Code
Debugging with PyCharm
See also
Performance testing for high traffic applications
Getting ready
How to do it...
See also
6
Integrating FastAPI with SQL Databases
Technical requirements
Setting up SQLAlchemy
Getting ready
How to do it...
How it works…
See also
Implementing CRUD operations
Getting ready
How to do it…
How it works…
Working with migrations
Getting ready
How to do it…
How it works…
See also
Handling relationships in SQL databases
Getting ready
How to do it…
See also
Optimizing SQL queries for performance
Getting ready
How to do it…
There’s more…
Securing sensitive data in SQL databases
Getting ready
How to do it…
See also
Handling transactions and concurrency
Getting ready
How to do it…
There’s more…
See also
7
Integrating FastAPI with NoSQL Databases
Technical requirements
Setting up MongoDB with FastAPI
Getting ready
How to do it…
See also
CRUD operations in MongoDB
Getting ready
How to do it…
See also
Handling relationships in NoSQL databases
Getting ready
How to do it…
See also
Working with indexes in MongoDB
Getting ready
How to do it…
How it works…
There’s more…
See also
Exposing sensitive data from NoSQL databases
Getting ready
How to do it…
There’s more…
See also
Integrating FastAPI with Elasticsearch
Getting ready
How to do it…
See also
Using Redis for caching in FastAPI
Getting ready
How to do it…
There’s more…
See also
8
Advanced Features and Best Practices
Technical requirements
Implementing dependency injection
Getting ready
How to do it…
How it works…
There’s more…
See also
Creating custom middleware
Getting ready…
How to do it…
How it works…
See also
Internationalization and localization
Getting ready
How to do it…
See also
Optimizing application performance
Getting ready
How to do it…
There’s more...
See also
Implementing rate limiting
Getting ready
How to do it…
There's more...
See also
Implementing background tasks
Getting ready
How to do it…
How it works…
See also
9
Working with WebSocket
Technical requirements
Setting up WebSockets in FastAPI
Getting ready
How to do it…
How it works…
See also
Sending and receiving messages over WebSockets
Getting ready
How to do it…
See also
Handling WebSocket connections and disconnections
Getting ready
How to do it…
Handling WebSocket errors and exceptions
Getting ready
How to do it…
See also
Implementing chat functionality with WebSockets
Getting ready
How to do it…
How it works…
See also
Optimizing WebSocket performance
Getting ready
How to do it…
There’s more…
See also
Securing WebSocket connections with OAuth2
Getting ready
How to do it…
See also
10
Integrating FastAPI with other Python Libraries
Technical requirements
Integrating FastAPI with gRPC
Getting ready
How to do it…
There’s more…
See also
Connecting FastAPI with GraphQL
Getting ready
How to do it…
See also
Using ML models with Joblib
Getting ready
How to do it…
See also
Integrating FastAPI with Cohere
Getting ready
How to do it…
See also
Integrating FastAPI with LangChain
Getting ready
How to do it…
See also
11
Middleware and Webhooks
Technical requirements
Creating custom ASGI middleware
Getting ready
How to do it…
How it works…
There’s more…
See also
Developing middleware for request modification
Getting ready
How to do it…
See also
Developing middleware for response modification
Getting ready
How to do it…
See also
Handling CORS with middleware
Getting ready
How to do it…
See also
Restricting incoming requests from hosts
Getting ready
How to do it…
See also
Implementing webhooks
Getting ready
How to do it…
How it works…
There’s more…
See also
12
Deploying and Managing FastAPI Applications
Technical requirements
Running the server with the FastAPI CLI
Getting ready
How to do it…
There’s more…
See also
Enabling HTTPS on FastAPI applications
Getting ready
How to do it…
There’s more…
See also
Running FastAPI applications in Docker containers
Getting ready
How to do it…
See also
Running the server across multiple workers
Getting ready
How to do it…
There’s more…
See also
Deploying your FastAPI application on the cloud
Getting started
How to do it…
There’s more…
See also
Shipping FastAPI applications with Hatch
Getting ready
How to do it…
There’s more…
See also
Index
Other Books You May Enjoy
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.
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.
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.
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.
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=.
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.
Get in touch
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected]
.
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
, select your book, click on the Errata Submission Form link, and enter the details.
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 [email protected]
with a link to the material.
If you