Skip to product information
Learning Backend Programming with FastAPI and Clean Architecture
Learning Backend Programming with FastAPI and Clean Architecture
Description
Book Introduction
Modern, fast, and easy to use FastAPI

Python-based FastAPI makes API creation easier than Flask and lighter than Django.
This book guides you through writing backend software with a clean architecture using FastAPI.
Clean Architecture requires more code as its layers increase, but FastAPI, which facilitates layer division, is a web framework ideal for implementing Clean Architecture. To create a TIL app, we first learn the concepts and features of FastAPI and Clean Architecture. Then, we move on to member registration, introducing DI, CRUD functionality, JWT, setting environment variables, implementing Clean Architecture layers, and writing tests.
By applying clean architecture, you will gain a powerful weapon called FastAPI.
  • You can preview some of the book's contents.
    Preview
","
index
Beta Reader Review ix
Beginning xii
About this book xiv

CHAPTER 1 Building a FastAPI Development Environment 1

1.1 Introduction to FastAPI 1
1.2 Virtual Environment and Dependency Management Using ForeTree 5
1.3 Hello, FastAPI 10
1.4 API Documentation 14
1.5 Database Setup 19
1.6 Applications to be built from the book: TIL 22
1.7 Final 23

CHAPTER 2 Clean Architecture 25

2.1 Why Architecture is Needed 25
2.2 Divide and Conquer 29
2.3 The four main layers of clean architecture 30
__2.3.1 Domain (Entity) Layer 32
__2.3.2 Application (Use Case) Layer 33
__2.3.3 Interface (Interface Adapter) Layer 34
__2.3.4 Infrastructure (Framework and Driver) Layer 35
2.4 Dependency Inversion Principle 36
2.5 Finish 37

CHAPTER 3: Signing Up 39

3.1 User Domain 39
3.2 Membership Use Case 41
__3.2.1 ULID 41
__3.2.2 User Save 42
__3.2.3 Duplicate User Check 44
__3.2.4 Password Encryption 45
3.3 Membership Registration Interface 47
__3.3.1 API Router 47
__3.3.2 Validation using Pydantic 48
__3.3.3 Change the status code of validation errors to 400 Bad Request 50
__3.3.4 Calling the Create User Use Case 52
__3.3.5 Class-Based Router 53
3.4 Persisting Member Information 54
__3.4.1 SQLAlchemy ORM Application 54
__3.4.2 Creating Tables and Revision Management with Alembic 56
__3.4.3 UserRepository Implementation 62
3.5 Finish 65

CHAPTER 4 Dependency Injection 67

4.1 Depends 68
4.2 dependency-injector 69
4.3 Conclusion 74

CHAPTER 5 Completing CRUD Functions for Member Resources 75

5.1 Added user memo properties 75
5.2 User Information Update 78
5.3 View user list 82
__5.3.1 Creating User Data for Testing 82
__5.3.2 User List Query 82
__5.3.3 Paging 84
5.4 Membership Withdrawal (User Deletion) 88
5.5 Pydantic Validation 91
__5.5.1 Request Parameter/Body Inspection 91
__5.5.2 Pydantic Response Model 95
5.6 Finish 97

CHAPTER 6 Asynchronous Programming 99

6.1 How to handle concurrency in Python 99
6.2 Asynchronous Processing 101 in FastAPI
6.3 Asynchronous Application Criteria 104
6.4 Conclusion 105

CHAPTER 7 Login 107

7.1 JWT 107
__7.1.1 Header 109
__7.1.2 Payload 110
__7.1.3 Signature 111
7.2 Login 112
7.3 JWT Authentication/Authorization 116
__7.3.1 Adding a Role to a Token 116
__7.3.2 API Authentication/Authorization for General Users 118
__7.3.3 Admin API Authentication/Authorization 121
7.4 Final 124

CHAPTER 8 ENVIRONMENT VARIABLES 125

8.1 dotenv 126
8.2 config.py: Environment Variable Management Module 127
8.3 Applying Environment Variables 128
8.4 Finish 130

CHAPTER 9 TIL Note 131

9.1 Domain Layer Implementation 132
9.2 Application Layer Implementation 134
9.3 Implementing the Interface Layer 139
__9.3.1 Creating Notes 140
__9.3.2 View note list/View note details 141
__9.3.3 Note Update 143
__9.3.4 Delete Note 144
__9.3.5 Searching notes by tag name 144
9.4 Implementing the Infrastructure Layer 145
__9.4.1 Note, Tag Table Modeling 145
__9.4.2 Table Migration 147
__9.4.3 Note Repository: Note Views 150
__9.4.4 Note Repository: Creating Notes 152
__9.4.5 Note Repository: Note Update 153
__9.4.6 Note Storage: Deleting Notes 154
__9.4.7 Note Storage: Viewing Notes by Tag Name 155
9.5 Finish 156

CHAPTER 10 Background Tasks: Sending Welcome Emails 157

10.1 BackgroundTasks 158
__10.1.1 What are BackgroundTasks? 158
__10.1.2 Sending Email with BackgroundTasks 160
10.2 Celery 166
__10.2.1 What is celery? 166
__10.2.2 Celery Preferences 169
__10.2.3 Example of executing a Celery task 171
__10.2.4 Sending Email with Celery 176
10.3 Final 178

CHAPTER 11 Middleware 179

11.1 Middleware Example 181
11.2 Context Variables 183
11.3 Logging to track user activity 186
__11.3.1 Middleware that stores user information as context variables 186
__11.3.2 Custom Logger 188
__11.3.3 Log output with user ID 190
11.4 Final 191

CHAPTER 12 TESTING 193

12.1 Domain Layer Testing 194
12.2 Application Layer Testing 196
__12.2.1 Test Double 197
__12.2.2 User Creation Use Case Testing 198
12.3 Interface Layer Testing 204
12.4 Infrastructure Layer Testing 206
12.5 Finish 209

Search 212
","
Detailed image
Detailed Image 1
","
Into the book
Once you create an API, you need to communicate it to other members who will use it.
If your organization is small and your API users are in the same space and understand the framework's code, sharing the source code is fine.
But how do you explain how to use an API when it's being used by front-end developers with different languages ​​and technology stacks? You can either describe it in text format or organize it in a spreadsheet for easy viewing.
Even today, many people still use this method.
But just like programs, once documentation becomes legacy, it is difficult to change.
The best way to distribute documentation is to generate API documentation from your source code, and FastAPI supports this without any special setup.
--- p.15

The dependency rule of clean architecture is that the direction of dependency is inward.
On the left side of Figure 2-1, there are arrows pointing inward from the outer layer.
This arrow indicates the direction of dependency.
The format of the data is also the same.
High-level data types can be used freely at low levels.
However, high-level components should not depend on low-level data types.
This is to isolate and protect internal elements from external changes.
Externally provided frameworks or libraries can be updated regardless of our will.
When such changes occur, if you are directly dependent on modules from that library, you will need to modify the internal elements as well.
--- p.36

The properties that allow users to update their information in the user resource are name and password.
Normally it would be weird to update your name, but in TIL it's not a problem since you'll be using your name as a nickname.
Let's assume that email is a unique value that cannot be changed because it is the value that the user uses to log in.
/ Let's implement it again starting from the domain layer.
First, declare a function to search for a user by user ID in IUserRepository and a function to update the user resource.
The reason we need a user search function is to find the target to update.
If the user does not exist in the database, an error occurs.

--- p.78

When operating a system, there are times when you need to assign various roles to logged-in users.
Access to resources is restricted based on roles, and roles are grouped and managed hierarchically.
/ Among the APIs listed above, users should only be able to call APIs that they have the authority to execute.
Users can only use the user deletion API, which means withdrawing membership, and the user information update API, which updates their information.
Since users should not be able to arbitrarily look up other people's information, let's say that only the administrator (p. application manager) can look up the user list.
Therefore, an authorization function that checks permissions is needed.
Establishing a proper authorization system is beyond the scope of this book.
In this book, we simply add a payload called role to the token and check the permissions by distinguishing whether the value is USER or ADMIN.

--- p.117

BackgroundTasks is a helper class provided by FastAPI.
This class allows you to perform tasks in the background after receiving a request from a client.
As we saw in the previous example, when processing an HTTP request, if the task is long-running or needs to be processed asynchronously, you may want to send a response to the client immediately and process the task in the background.
This will improve the usability of the client.
That is, you can continue with other tasks without waiting for the request to complete.
/ The BackgroundTasks class makes it easy to handle these tasks in your FastAPI app.
As you can see in the following example, you can inject it as a parameter to your endpoint function and let FastAPI handle the rest.
It's the same as when you directly inject and use the Request object.

--- p.158

Celery (p.Celery) is a distributed task queue (p.distributed task queue) based on Unix systems, used to process and manage asynchronous tasks.
It mainly handles or schedules background tasks and executes them in a distributed environment.
In addition to Celery, other Python-based messaging systems worth considering include Redis Queue (p.Redis queue, RQ), Dramatic (p.Dramatiq), Huey (p.huey), and AIOHTTP.
In addition, Kafka--- p.Kafka) is gaining popularity recently as it boasts high performance even in large-scale systems.
--- pp.166-167
","
Publisher's Review
Eliminate Spaghetti Code with FastAPI and Clean Architecture

FastAPI ranked 14th in the 'Web Frameworks and Technologies' category conducted by Stack Overflow in 2024.
Among Python web frameworks, it ranks third after Flask and Django, and has been rapidly catching up with Flask and Django since its debut in 2018.
Even though version 1 has not yet been officially released, it has many advantages, including excellent performance and intuitive usability, and is being adopted by many companies, including Netflix, Uber, and Cisco Systems.


Since FastAPI already has a very well-organized official documentation, this book focuses on software structure design using FastAPI and clean architecture that maximizes maintainability and scalability.
One of the most important factors in backend development today is an efficient and scalable architecture.
A system without a 'proper' architecture is nothing more than a big lump of spaghetti code and mud.
This 12-chapter book presents methods for creating maintainable and stable systems by applying clean architecture based on the powerful features of FastAPI.

Chapter 1 briefly looks at the features of FastAPI, how to build a development environment using Fortree, and the structure of the TIL app that will be created in the book.
In Chapter 2, we will learn about clean architecture by dividing it into domain, application, interface, and infrastructure layers.
In Chapter 3, we will implement membership registration, one of the core functions of the TIL app service, using FastAPI while applying clean architecture.

In Chapter 4, dependency injection is introduced to the membership registration function implemented in Chapter 3, and in Chapter 5, an API for searching, modifying, and deleting user information is completed using Pydantic.
Chapter 6 looks at an example of performing asynchronous processing, one of the methods for handling concurrency in FastAPI.
In Chapter 7, we will learn about and apply JWT, which is most commonly used for authentication/authorization, while creating a function that allows users who have signed up for the TIL service to log in.

In Chapter 8, we will look at managing hard-coded values ​​in the code as environment variables, and in Chapter 9, we will look at an example of extending the functionality of the TIL service to handle user-written post (note) resources.
Chapter 10 covers background task methods that can be applied when developing a server with FastAPI, and Chapter 11 covers how to utilize middleware.
Finally, in Chapter 12, we write test code for the code we've written to make it easy to perform repetitive tests and build secure systems.


This book is a useful guide for developers who are considering better software design methods beyond simple functional implementation through FastAPI and Clean Architecture.
It will be of practical help to developers who want to build stable and scalable backend systems, especially in the rapidly changing web development environment.


Key Contents

● Concepts and functions of FastAPI and Clean Architecture
● Validation using Pydantic
● DI method and application method
● Using JWT for authentication/authorization
Asynchronous processing using Celery
● How to use middleware that makes HTTP requests and responses easier
● How to apply unit tests by layer
"]
GOODS SPECIFICS
- Date of issue: October 25, 2024
- Page count, weight, size: 232 pages | 580g | 188*245*15mm
- ISBN13: 9791193926529
- ISBN10: 1193926521

You may also like

카테고리