Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Python Microservices with FastAPI
Python Microservices with FastAPI

Python Microservices with FastAPI: Design production-ready, AI-enabled microservices with Python

Arrow left icon
Profile Icon Giunio De Luca Profile Icon Igor Benav
Arrow right icon
Early Access Early Access Publishing in Jun 2026
Can$41.39 Can$45.99
eBook Jun 2026 1st Edition
eBook
Can$41.39 Can$45.99
Paperback
Can$56.99
Subscription
Free Trial
Arrow left icon
Profile Icon Giunio De Luca Profile Icon Igor Benav
Arrow right icon
Early Access Early Access Publishing in Jun 2026
Can$41.39 Can$45.99
eBook Jun 2026 1st Edition
eBook
Can$41.39 Can$45.99
Paperback
Can$56.99
Subscription
Free Trial
eBook
Can$41.39 Can$45.99
Paperback
Can$56.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB format
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Python Microservices with FastAPI

1

Launching the Platform: FastAPI Project Basics

Welcome to the first chapter of our journey into modern microservices. Whether you’re a developer eager for hands-on skills or an architect seeking a clear framework, this chapter is your starting point.

We’ll cut through the buzz and misconceptions to explain what microservices truly are and why they matter. You’ll explore the core principles behind microservice design, what distinguishes successful architectures, and how to determine if this approach is right for your platform.

By the end of this chapter, you’ll have a clear understanding of what microservices are, and what they are not. You’ll also know how to kickstart a FastAPI application and set up your development environment for the best experience from day one. Furthermore, you’ll gain an overview of modern Python package managers.

In this chapter, we’ll cover the following main topics:

  • Refresh some conceptions about Microservices...

Technical requirements

Before we dive into the hands-on work, let’s take a moment to talk about what you’ll need to successfully follow along with this chapter.

  • You should already be familiar with Python; the code is tested with Python 3.13 .
  • Also, being familiar with a virtual environment or simply an isolated environment could help, but is not mandatory
  • You should have your code editor already set up: whether you love VS Code, Cursor, PyCharm, Vim, or even Emacs, any editor that supports Python will work. The important thing is that you can move quickly and comfortably through your files.
  • Being familiar with a command-line interface is an advantage since much of your interaction will happen in the terminal or command prompt. If you’re new to it, don’t worry—mastery comes with practice, and every step you take here deepens your understanding.
  • Internet access: you’ll need it for installing dependencies, checking documentation, and occasionally...

What makes a Modern Microservice Project?

Before diving into project setup and code, let’s clarify what this book is really about: microservices.

In recent years, the term is everywhere—conference talks, architecture diagrams, job interviews, you name it—but it’s often misunderstood.

Let’s take a moment to unpack what a microservice is, what it isn’t, and why we’re choosing this architecture for our Platform.

According to Martin Fowler from the book Patterns of Enterprise Application Architecture:

The microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API.

We can think of a microservice as an independently deployable unit of software that focuses on doing one business capability well. It runs in its own process, communicates with other services over the network...

Start the Project with uv

When building complex systems, it's much easier if you have a solid approach to organizing and managing your code. This helps keep things less complicated and makes development more enjoyable.

One great advantage for developers is working with isolated and reproducible environments. These provide several benefits:

  • They prevent changes to your system's main Python installation
  • They ensure that dependencies stay consistent across different machines.
  • They allow different projects or microservices to use their own versions of dependencies.
  • They make sure tools like linters and test runners work consistently (we'll discuss this more later).

Alongside isolated environments, a proper packaging tool is how you communicate the structure, metadata, and dependencies of your microservice.

Today we rely on the PEP 621 standard (https://peps.python.org/pep-0621/) that defines pyproject.toml file as the modern, canonical way to define specifications for a Python...

Introducing FastAPI

When building microservices, choosing the right web framework is essential. It should be lightweight yet robust, developer-friendly yet ready.

FastAPI perfectly fits this balance. FastAPI is a modern, high-performance web framework for building APIs with Python, relying on standard Python type hints.

It is designed from the ground up to support asynchronous programming, automatic OpenAPI documentation, and rapid execution powered by Starlette and Pydantic.

In this section, you will build your first endpoint with FastAPI and explore some of the core concepts that make FastAPI not only convenient but also an ideal framework for microservice architectures.

FastAPI combines speed with an excellent developer experience. Here’s why it stands out:

  • Asynchronous-first design utilizing async / await syntax
  • Type hints drive validation, documentation, and support for major Integrated Development Environments (IDEs)
  • Automatic generation of OpenAPI (Swagger) and ReDoc documentation...

Creating the First Test

In microservice-based architectures, managing a collection of independent, communicating services makes automated testing essential and unit tests are the first line of defense against regressions, integration bugs, and broken APIs.

They empower you to iterate with confidence, ensuring that existing behavior continues to work every time you run your code.

Why test? Here are a few good reasons:

  • Validate behavior: Confirm that your endpoints return the expected results
  • Detect regressions early: Prevent future changes from breaking existing logic
  • Enable refactoring: Refactor code with the assurance that nothing else is affected
  • Document expectations: Tests serve as executable specifications

For microservices, where interdependencies can be subtle and breaking changes potentially disastrous, maintaining a reliable suite of tests is critical, making it a wise investment to set up your test environment from the start.

Within the Python ecosystem, the pytest framework...

Setting up Formatters Linters, and Static Type Checkers

In coding, clarity, maintainability, and predictability are essential. When multiple developers work across many services, it's crucial that anyone can quickly understand, test, and modify the code with confidence. The simplest way to enable this is by enforcing consistent coding standards through automated tools.

This section introduces the essential tools every Python project should use: a formatter, an import sorter, a linter, and a static type checker. These tools will be added to your project as development dependencies and configured so they can be used manually, through your editor, or in a Continuous Integration (CI) pipeline.

Throughout this book, we will use Ruff for formatting, imports sorting, and linting. To add the ruff package as a development dependency, run:

uv add ruff --dev

Ruff can both check and format your code, ensuring it complies with your chosen rules. By default, the line length is set to 88 characters...

Overview of other Package Manager tools

We have used uv and will use it for the rest of the book to create projects, handling dependencies, running commands, etc.

However, Python has a rich, though sometimes confusing, ecosystem of tools to manage packages and environments.

This section introduces the most commonly used ones, helping you understand where each shines and how to get started.

pip + venv

pip is the default package manager while venv is the default library to manage a virtual environment that comes with the built-in Python distribution.

Their combination is the most basic method to manage environments and packages available in every Python 3 installation. To use it, you simply need to have Python installed on your machine.

The venv module creates isolated environments, while the pip command installs packages within them. Being built-in, this approach remains a reliable option for creating simple scripts or prototyping. It provides full control and transparency since it does...

Summary

Throughout this chapter, we have explored essential concepts related to microservices, kickstarted a service using uv, and built our first FastAPI endpoint. We also examined supporting development tools and took a comprehensive look at the evolving Python package management ecosystem.

By mastering these skills, you are now equipped to streamline project setup, enhance collaboration, and avoid common dependency pitfalls—key competencies for any Python developer aiming for efficient, maintainable codebases.

With these fundamentals in place, we are ready to move forward and begin building a more interactive application that handles request parameters and cookies in the next chapter.

Further reading

The definition of microservice is not unique.

For everything related to FastAPI, have a look at the official documentation:

For each of the package manager tools, refer to their respective documentation link:

Left arrow icon Right arrow icon

Key benefits

  • Design clear, evolvable services, and explain decisions your team trusts
  • Ship reliable backends with the right data stores, async jobs, auth, testing, and observability
  • Add practical AI features (RAG, agents) that reduces support and drives measurable value

Description

This book shows you how to turn an idea into a reliable product. This is a playbook for practical progress. Choose what to ship now, what to delay, and how to avoid risky changes. Keep services tidy, naming clear, and tests small but useful. You will build a realistic end-to-end system step by step, following the evolution of a babysitting marketplace platform with sign-up, search, booking, messaging, and payments delivered in steady increments. When it is time to add intelligence, you learn practical ways to use AI for customer support, recommendations, and operational insights. The focus stays on measurable value, not hype, while keeping performance, costs, and reliability predictable in production. Your guides are Giunio De Luca, PhD, author of Packt’s FastAPI Cookbook and an architect who has shipped systems across research, sports, and energy, and Igor “Benav” Magalhães, founder of Benav Labs and maintainer of widely used open-source tools. They share patterns they rely on when deadlines are real and reliability matters. By the end, you will not just know FastAPI. You will think like a senior engineer, plan delivery with confidence, avoid common traps, measure what matters, and run a backend platform that users trust and teams enjoy maintaining.

Who is this book for?

For Python developers who want to move beyond monoliths and ship scalable backends. Ideal for engineers aiming for lead/architect roles who need practical patterns for clean code, async workflows, and multi-database design. You’ll learn how to add secure authentication, real-time features, and AI capabilities RAG chat, agents, and analytics without losing testability or performance. Basic Python and web API knowledge is recommended.

What you will learn

  • Set up a microservice from scratch with modern Python tooling
  • Build RESTful APIs with clean boundaries, DI, and type-safe models
  • Design multiple services and compose them through a gateway
  • Model data with PostgreSQL, MongoDB, and vector stores
  • Scale with async I/O, background tasks, queues, and WebSockets
  • Secure services with OAuth2/JWT and role-based access
  • Test, profile, observe, and deploy with confidence
  • Add AI features including RAG chatbots, agents, and analytics

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 26, 2026
Edition : 1st
Language : English
ISBN-13 : 9781835463390
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB format
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Jun 26, 2026
Edition : 1st
Language : English
ISBN-13 : 9781835463390
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Table of Contents

4 Chapters
Welcome to Packt Early Access Chevron down icon Chevron up icon
Chapter 1: Launching the Platform: FastAPI Project Basics Chevron down icon Chevron up icon
Chapter 2: Creating the Parents’ Portal Chevron down icon Chevron up icon
Chapter 4: Dependency Injection in FastAPI Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon
Modal Close icon