Sherwin John Tragura - Building Python Microservices with FastAPI Build secure, scalable, and structured Python microservices from design concepts to infrastructure-Packt Publishing - ebooks Account
Setting Up FastAPI for Starters 3 Technical requirements 4 Setting up the development environment 4 Initializing and configuring FastAPI 5 Designing and implementing REST APIs 6 Managing user requests and server response 10 Parameter type declaration 10 Path parameters 10 Query parameters 12 Default parameters 14 Optional parameters 15 Mixing all types of parameters 16 Request body 17 Request headers 19 Response data 20 Handling form parameters 22 Managing cookies 23 Summary 24 2 Exploring the Core Features 25 Technical requirements 26 Structuring and organizing huge projects 26 Implementing the API services 27 Importing the module components 28 Implementing the new main.py file 29 Managing API-related exceptions 30
Table of Contents
viii
A single status code response 30 Multiple status codes 32 Raising HTTPException 33 Custom exceptions 34 A default handler override 37 Converting objects to JSON- compatible types 38 Managing API responses 39 Creating background processes 41 Using asynchronous path operations 43 Applying middleware to filter path operations 44 Summary 46 3 Investigating Dependency Injection 47 Technical requirements 48 Applying IoC/DI 48 Injecting a dependency function 49 Injecting a callable class 50 Building nested dependencies 51 Caching the dependencies 53 Declaring Depends() parameter types 54 Injecting asynchronous dependencies 55 Exploring ways of injecting dependencies 56 Dependency injection on services 56 Dependency injection on path operators 57 Dependency injection on routers 58 Dependency injection on main.py 61 Organizing a project based on dependencies 62 The model layer 63 The repository layer 64 The repository factory methods 66 The service layer 67 The REST API and the service layer 67 The actual project structure 68 Using third-party containers 69 Using configurable containers – Dependency Injector 69 Using a simple configuration – Lagom 74 The FastAPI and Lagom integration 74 Scoping of dependables 75 Summary 76 4 Building the Microservice Application 77 Technical requirements 78 Applying the decomposition pattern 78 Creating the sub-applications 80 Mounting the submodules 81 Creating a common gateway 82
Table of Contents
ix
Implementing the main endpoint 82 Evaluating the microservice ID 83 Applying the exception handlers 84 Centralizing the logging mechanism 86 Utilizing the Loguru module 86 Building the logging middleware 88 Consuming the REST API services 90 Using the httpx module 91 Using the requests module 92 Applying the domain modeling approach 94 Creating the layers 94 Identifying the domain models 95 Building the repository and service layers 97 Using the factory method pattern 100 Managing a microservice’s configuration details 100 Storing settings as class attributes 101 Storing settings in the properties file 102 Summary 104 Part 2: Data-Centric and Communication-Focused Microservices Concerns and Issues 5 Connecting to a Relational Database 107 Technical requirements 108 Preparing for database connectivity 108 Creating CRUD transactions using SQLAlchemy 110 Installing the database driver 110 Setting up the database connection 110 Initializing the session factory 111 Defining the Base class 112 Building the model layer 112 Implementing the repository layer 116 Running the transactions 120 Creating tables 123 Implementing async CRUD transactions using SQLAlchemy 124 Installing the asyncio-compliant database drivers 124 Setting up the database’s connection 124 Creating the session factory 125 Creating the Base class and the model layer 125 Building the repository layer 126
Table of Contents
x
Running the CRUD transactions 129 Using GINO for async transactions 130 Installing the database driver 131 Establishing the database connection 131 Building the model layer 131 Implementing the CRUD transactions 135 Running the CRUD transactions 138 Creating the tables 139 Using Pony ORM for the repository layer 140 Installing the database driver 140 Creating the database’s connectivity 141 Defining the model classes 141 Implementing the CRUD transactions 144 Running the repository transactions 148 Creating the tables 148 Building the repository using Peewee 148 Installing the database driver 148 Creating the database connection 149 Creating the tables and the domain layer 150 Implementing the CRUD transactions 153 Running the CRUD transaction 155 Applying the CQRS design pattern 156 Defining the handler interfaces 156 Creating the command and query classes 156 Creating the command and query handlers 157 Accessing the handlers 158 Summary 160 6 Using a Non-Relational Database 161 Technical requirements 162 Setting up the database environment 162 Applying the PyMongo driver for synchronous connections 165 Setting up the database connectivity 165 Building the model layer 166 Implementing the repository layer 174 Running the transactions 179 Creating async CRUD transactions using Motor 182 Setting up the database connectivity 182 Creating the model layer 183 Running the CRUD transactions 185 Implementing CRUD transactions using MongoEngine 186 Establishing database connection 187 Building the model layer 187 Implementing the CRUD transactions 190 Running the CRUD transactions 194
Table of Contents
xi
Implementing async transactions using Beanie 195 Creating the database connection 195 Defining the model classes 196 Implementing the CRUD transactions 198 Running the repository transactions 200 Building async repository for FastAPI using ODMantic 200 Creating the database connection 201 Creating the model layer 201 Implementing the CRUD transactions 202 Running the CRUD transaction 205 Creating CRUD transactions using MongoFrames 206 Creating the database connection 206 Building the model layer 207 Creating the repository layer 208 Applying the repository layer 211 Summary 212 7 Securing the REST APIs 213 Technical requirements 214 Implementing Basic and Digest authentication 214 Using Basic authentication 214 Using Digest authentication 218 Implementing password-based authentication 222 Installing the python-multipart module 222 Using OAuth2PasswordBearer and OAuth2PasswordRequestForm 222 Executing the login transaction 223 Securing the endpoints 226 Applying JWTs 228 Generating the secret key 228 Creating the access_token 228 Creating the login transaction 229 Accessing the secured endpoints 230 Creating scope-based authorization 231 Customizing the OAuth2 class 231 Building the permission dictionary 232 Implementing the login transaction 233 Applying the scopes to endpoints 234 Building the authorization code flow 236 Applying OAuth2Authorization CodeBearer 236 Implementing the authorization request 237 Implementing the authorization code response 238 Applying the OpenID Connect specification 240 Using HTTPBearer 240 Installing and configuring the Keycloak environment 240 Setting the Keycloak realm and clients 240 Creating users and user roles 242 Assigning roles to clients 243 Creating user permissions through scopes 244
Table of Contents
xii
Integrating Keycloak with FastAPI 245 Implementing the token verification 247 Integrating Auth0 with FastAPI 249 Integrating Okta with FastAPI 250 Using built-in middlewares for authentication 250 Summary 251 8 Creating Coroutines, Events, and Message-Driven Transactions 253 Technical requirements 254 Implementing coroutines 254 Applying coroutine switching