Building Python Microservices with FastAPI

Book description

Discover the secrets of building Python microservices using the FastAPI framework

Key Features

  • Provides a reference that contains definitions, illustrations, comparative analysis, and the implementation of real-world apps
  • Covers concepts, core details, and advanced integration and design-related topics
  • Imparts context, app templates, suggestions, and insights that are helpful to actual projects

Book Description

FastAPI is an Asynchronous Server Gateway Interface (ASGI)-based framework that can help build modern, manageable, and fast microservices. Because of its asynchronous core platform, this ASGI-based framework provides the best option when it comes to performance, reliability, and scalability over the WSGI-based Django and Flask. When working with Python, Flask, and Django microservices, you'll be able to put your knowledge to work with this practical guide to building seamlessly manageable and fast microservices.

You'll begin by understanding the background of FastAPI and learning how to install, configure, and use FastAPI to decompose business units. You'll explore a unique and asynchronous REST API framework that can provide a better option when it comes to building microservices. After that, this book will guide you on how to apply and translate microservices design patterns in building various microservices applications and RESTful APIs using the FastAPI framework.

By the end of this microservices book, you'll be able to understand, build, deploy, test, and experiment with microservices and their components using the FastAPI framework.

What you will learn

  • Understand, orient, and implement REST APIs using the basic components of the FastAPI framework
  • Build asynchronous as well as synchronous REST services using the built-in pydantic module and asyncio support
  • Create small-scale and large-scale microservices applications using features supported by FastAPI
  • Build event-driven and message-driven applications using the framework
  • Create an asynchronous and synchronous data layer with both relational and NoSQL databases
  • Perform numerical and symbolic computations with FastAPI

Who this book is for

This book is for Python web developers, advanced Python developers, and backend developers using Flask or Django who want to learn how to use the FastAPI framework to implement microservices. Readers familiar with the REST API and microservices will also benefit from this book. Some parts of the book contain general concepts, processes, and instructions that intermediate-level developers and Python enthusiasts can relate to as well.

Table of contents

  1. Building Python Microservices with FastAPI
  2. Contributors
  3. About the author
  4. About the reviewers
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
    4. Download the example code files
    5. Download the color images
    6. Conventions used
    7. Get in touch
    8. Share your thoughts
  6. Part 1: Application-Related Architectural Concepts for FastAPI microservice development
  7. Chapter 1: Setting Up FastAPI for Starters
    1. Technical requirements
    2. Setting up the development environment
    3. Initializing and configuring FastAPI
    4. Designing and implementing REST APIs
    5. Managing user requests and server response
      1. Parameter type declaration
      2. Path parameters
      3. Query parameters
      4. Default parameters
      5. Optional parameters
      6. Mixing all types of parameters
      7. Request body
      8. Request headers
      9. Response data
    6. Handling form parameters
    7. Managing cookies
    8. Summary
  8. Chapter 2: Exploring the Core Features
    1. Technical requirements
    2. Structuring and organizing huge projects
      1. Implementing the API services
      2. Importing the module components
      3. Implementing the new main.py file
    3. Managing API-related exceptions
      1. A single status code response
      2. Multiple status codes
      3. Raising HTTPException
      4. Custom exceptions
      5. A default handler override
    4. Converting objects to JSON-compatible types
    5. Managing API responses
    6. Creating background processes
    7. Using asynchronous path operations
    8. Applying middleware to filter path operations
    9. Summary
  9. Chapter 3: Investigating Dependency Injection
    1. Technical requirements
    2. Applying IoC/DI
      1. Injecting a dependency function
      2. Injecting a callable class
      3. Building nested dependencies
      4. Caching the dependencies
      5. Declaring Depends() parameter types
      6. Injecting asynchronous dependencies
    3. Exploring ways of injecting dependencies
      1. Dependency injection on services
      2. Dependency injection on path operators
      3. Dependency injection on routers
      4. Dependency injection on main.py
    4. Organizing a project based on dependencies
      1. The model layer
      2. The repository layer
      3. The repository factory methods
      4. The service layer
      5. The REST API and the service layer
      6. The actual project structure
    5. Using third-party containers
      1. Using configurable containers – Dependency Injector
      2. Using a simple configuration – Lagom
      3. The FastAPI and Lagom integration
    6. Scoping of dependables
    7. Summary
  10. Chapter 4: Building the Microservice Application
    1. Technical requirements
    2. Applying the decomposition pattern
      1. Creating the sub-applications
    3. Mounting the submodules
    4. Creating a common gateway
    5. Implementing the main endpoint
    6. Evaluating the microservice ID
    7. Applying the exception handlers
    8. Centralizing the logging mechanism
      1. Utilizing the Loguru module
    9. Building the logging middleware
      1. Consuming the REST API services
    10. Using the httpx module
    11. Using the requests module
    12. Applying the domain modeling approach
    13. Creating the layers
    14. Identifying the domain models
    15. Building the repository and service layers
      1. Using the factory method pattern
    16. Managing a microservice’s configuration details
      1. Storing settings as class attributes
      2. Storing settings in the properties file
    17. Summary
  11. Part 2: Data-Centric and Communication-Focused Microservices Concerns and Issues
  12. Chapter 5: Connecting to a Relational Database
    1. Technical requirements
    2. Preparing for database connectivity
    3. Creating CRUD transactions using SQLAlchemy
      1. Installing the database driver
      2. Setting up the database connection
      3. Initializing the session factory
      4. Defining the Base class
      5. Building the model layer
      6. Implementing the repository layer
      7. Running the transactions
      8. Creating tables
    4. Implementing async CRUD transactions using SQLAlchemy
      1. Installing the asyncio-compliant database drivers
      2. Setting up the database’s connection
      3. Creating the session factory
      4. Creating the Base class and the model layer
      5. Building the repository layer
      6. Running the CRUD transactions
    5. Using GINO for async transactions
      1. Installing the database driver
      2. Establishing the database connection
      3. Building the model layer
      4. Implementing the CRUD transactions
      5. Running the CRUD transactions
      6. Creating the tables
    6. Using Pony ORM for the repository layer
      1. Installing the database driver
      2. Creating the database’s connectivity
      3. Defining the model classes
      4. Implementing the CRUD transactions
      5. Running the repository transactions
      6. Creating the tables
    7. Building the repository using Peewee
      1. Installing the database driver
      2. Creating the database connection
      3. Creating the tables and the domain layer
      4. Implementing the CRUD transactions
      5. Running the CRUD transaction
    8. Applying the CQRS design pattern
      1. Defining the handler interfaces
      2. Creating the command and query classes
      3. Creating the command and query handlers
      4. Accessing the handlers
    9. Summary
  13. Chapter 6: Using a Non-Relational Database
    1. Technical requirements
    2. Setting up the database environment
    3. Applying the PyMongo driver for synchronous connections
      1. Setting up the database connectivity
      2. Building the model layer
      3. Implementing the repository layer
      4. Running the transactions
    4. Creating async CRUD transactions using Motor
      1. Setting up the database connectivity
      2. Creating the model layer
      3. Running the CRUD transactions
    5. Implementing CRUD transactions using MongoEngine
      1. Establishing database connection
      2. Building the model layer
      3. Implementing the CRUD transactions
      4. Running the CRUD transactions
    6. Implementing async transactions using Beanie
      1. Creating the database connection
      2. Defining the model classes
      3. Implementing the CRUD transactions
      4. Running the repository transactions
    7. Building async repository for FastAPI using ODMantic
      1. Creating the database connection
      2. Creating the model layer
      3. Implementing the CRUD transactions
      4. Running the CRUD transaction
    8. Creating CRUD transactions using MongoFrames
      1. Creating the database connection
      2. Building the model layer
      3. Creating the repository layer
      4. Applying the repository layer
    9. Summary
  14. Chapter 7: Securing the REST APIs
    1. Technical requirements
    2. Implementing Basic and Digest authentication
      1. Using Basic authentication
      2. Using Digest authentication
    3. Implementing password-based authentication
      1. Installing the python-multipart module
      2. Using OAuth2PasswordBearer and OAuth2PasswordRequestForm
      3. Executing the login transaction
      4. Securing the endpoints
    4. Applying JWTs
      1. Generating the secret key
      2. Creating the access_token
      3. Creating the login transaction
      4. Accessing the secured endpoints
    5. Creating scope-based authorization
      1. Customizing the OAuth2 class
      2. Building the permission dictionary
      3. Implementing the login transaction
      4. Applying the scopes to endpoints
    6. Building the authorization code flow
      1. Applying OAuth2AuthorizationCodeBearer
      2. Implementing the authorization request
      3. Implementing the authorization code response
    7. Applying the OpenID Connect specification
      1. Using HTTPBearer
      2. Installing and configuring the Keycloak environment
      3. Setting the Keycloak realm and clients
      4. Creating users and user roles
      5. Assigning roles to clients
      6. Creating user permissions through scopes
      7. Integrating Keycloak with FastAPI
      8. Implementing the token verification
      9. Integrating Auth0 with FastAPI
      10. Integrating Okta with FastAPI
    8. Using built-in middlewares for authentication
    9. Summary
  15. Chapter 8: Creating Coroutines, Events, and Message-Driven Transactions
    1. Technical requirements
    2. Implementing coroutines
      1. Applying coroutine switching
      2. Designing asynchronous transactions
      3. Using the HTTP/2 protocol
    3. Creating asynchronous background tasks
      1. Using the coroutines
      2. Creating multiple tasks
    4. Understanding Celery tasks
      1. Creating and configuring the Celery instance
      2. Creating the task
      3. Calling the task
      4. Starting the worker server
      5. Monitoring the tasks
    5. Building message-driven transactions using RabbitMQ
      1. Creating the Celery instance
      2. Monitoring AMQP messaging
    6. Building publish/subscribe messaging using Kafka
      1. Running the Kafka broker and server
      2. Creating the topic
      3. Implementing the publisher
      4. Running a consumer on a console
    7. Implementing asynchronous Server-Sent Events (SSE)
    8. Building an asynchronous WebSocket
      1. Implementing the asynchronous WebSocket endpoint
      2. Implementing the WebSocket client
    9. Applying reactive programming in tasks
      1. Creating the Observable data using coroutines
      2. Creating background process
      3. Accessing API resources
    10. Customizing events
      1. Defining the startup event
      2. Defining shutdown events
    11. Summary
  16. Part 3: Infrastructure-Related Issues, Numerical and Symbolic Computations, and Testing Microservices
  17. Chapter 9: Utilizing Other Advanced Features
    1. Technical requirements
    2. Applying session management
      1. Creating user sessions
      2. Managing session data
      3. Removing the sessions
      4. Customizing BaseHTTPMiddleware
    3. Managing the CORS mechanism
    4. Customizing APIRoute and Request
      1. Managing body, form, or JSON data
      2. Encrypting and decrypting the message body
    5. Choosing the appropriate responses
      1. Setting up the Jinja2 template engine
      2. Setting up the static resources
      3. Creating the template layout
      4. Using ORJSONResponse and UJSONResponse
    6. Applying the OpenAPI 3.x specification
      1. Extending the OpenAPI schema definition
      2. Using the internal code base properties
      3. Using the Query, Form, Body, and Path functions
    7. Testing the API endpoints
      1. Writing the unit test cases
      2. Mocking the dependencies
      3. Running test methods
    8. Summary
  18. Chapter 10: Solving Numerical, Symbolic, and Graphical Problems
    1. Technical requirements
    2. Setting up the projects
      1. Using the Piccolo ORM
      2. The Beanie ODM
    3. Implementing symbolic computations
      1. Creating symbolic expressions
      2. Solving linear expressions
      3. Solving non-linear expressions
      4. Solving linear and non-linear inequalities
    4. Creating arrays and DataFrames
      1. Applying NumPy’s linear system operations
      2. Applying the pandas module
    5. Performing statistical analysis
    6. Generating CSV and XLSX reports
    7. Plotting data models
    8. Simulating a BPMN workflow
      1. Designing the BPMN workflow
      2. Implementing the workflow
    9. Using GraphQL queries and mutations
      1. Setting up the GraphQL platform
      2. Creating the record insertion, update, and deletion
      3. Implementing the query transactions
      4. Running the CRUD transactions
    10. Utilizing the Neo4j graph database
      1. Setting the Neo4j database
      2. Creating the CRUD transactions
    11. Summary
  19. Chapter 11: Adding Other Microservice Features
    1. Technical requirements
    2. Setting up the virtual environment
    3. Checking the API properties
    4. Implementing open tracing mechanisms
    5. Setting up service registry and client-side service discovery
      1. Implementing client-side service discovery
      2. Setting up the Netflix Eureka service registry
    6. Deploying and running applications using Docker
      1. Generating the requirements.txt file
      2. Creating the Docker image
      3. Using the Mongo Docker image
      4. Creating the containers
    7. Using Docker Compose for deployment
    8. Using NGINX as an API Gateway
    9. Integrating Flask and Django sub-applications
    10. Summary
  20. Index
    1. Why subscribe?
  21. Other Books You May Enjoy
    1. Packt is searching for authors like you
    2. Share your thoughts

Product information

  • Title: Building Python Microservices with FastAPI
  • Author(s): Sherwin John C. Tragura
  • Release date: August 2022
  • Publisher(s): Packt Publishing
  • ISBN: 9781803245966