High-Performance Web Apps with FastAPI The Asynchronous Web Framework Based on Modern Python — Malhar Lathkar
High-Performance Web Apps with FastAPI The Asynchronous Web Framework Based on Modern Python Malhar Lathkar
High-Performance Web Apps with FastAPI: The Asynchronous Web Framework Based on Modern Python ISBN-13 (pbk): 978-1-4842-9177-1 ISBN-13 (electronic): 978-1-4842-9178-8 https://doi.org/10.1007/978-1-4842-9178-8 Copyright © 2023 by Malhar Lathkar This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director, Apress Media LLC: Welmoed Spahr Acquisitions Editor: Divya Modi Development Editor: James Markham Coordinating Editor: Divya Modi Cover designed by eStudioCalamar Cover image designed by Piaxaby Distributed to the book trade worldwide by Springer Science+Business Media New York, 1 New York Plaza, Suite 4600, New York, NY 10004-1562, USA. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail booktranslations@springernature.com; for reprint, paperback, or audio rights, please e-mail bookpermissions@springernature.com. Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales. Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book’s product page, located at https://github.com/ Apress/Build-High-Performance-Web-Apps-with-FastAPI-by-Malhar-Lathkar. For more detailed information, please visit http://www.apress.com/source-code. Printed on acid-free paper Malhar Lathkar Nanded, Maharashtra, India
Dedicated to my late father, Shri V. K. Lathkar. You stood behind me like a rock. It helped me to get rid of fear of failure.
v Table of Contents About the Author �������������������������������������������������������������������������������xiii About the Technical Reviewer ������������������������������������������������������������xv Acknowledgments ����������������������������������������������������������������������������xvii Introduction ���������������������������������������������������������������������������������������xix Chapter 1: Introduction to FastAPI �������������������������������������������������������1 Type Hints �������������������������������������������������������������������������������������������������������������2 The typing Module �������������������������������������������������������������������������������������������6 Asynchronous Processing �������������������������������������������������������������������������������������8 The asyncio Module �����������������������������������������������������������������������������������������8 ASGI ���������������������������������������������������������������������������������������������������������������11 About REST Architecture �������������������������������������������������������������������������������������13 What Is an API? ����������������������������������������������������������������������������������������������14 REST ��������������������������������������������������������������������������������������������������������������17 REST Constraints �������������������������������������������������������������������������������������������17 HTTP Verbs ����������������������������������������������������������������������������������������������������������19 POST Method �������������������������������������������������������������������������������������������������19 GET Method ���������������������������������������������������������������������������������������������������20 PUT Method ���������������������������������������������������������������������������������������������������20 DELETE Method ���������������������������������������������������������������������������������������������21 FastAPI Dependencies ����������������������������������������������������������������������������������������21 Starlette ���������������������������������������������������������������������������������������������������������22
vi Pydantic ���������������������������������������������������������������������������������������������������������23 Uvicorn ����������������������������������������������������������������������������������������������������������23 Installation of FastAPI �����������������������������������������������������������������������������������������24 Summary�������������������������������������������������������������������������������������������������������������28 Chapter 2: Getting Started with FastAPI ���������������������������������������������29 Hello World ����������������������������������������������������������������������������������������������������������30 Create an Application Object �������������������������������������������������������������������������30 Path Operation Decorator ������������������������������������������������������������������������������30 Path Operation Function ��������������������������������������������������������������������������������32 Start Uvicorn ��������������������������������������������������������������������������������������������������32 Externally Visible Server ��������������������������������������������������������������������������������34 Interactive API Docs ��������������������������������������������������������������������������������������������36 Swagger UI ����������������������������������������������������������������������������������������������������37 Redoc ������������������������������������������������������������������������������������������������������������42 JSON Schema ������������������������������������������������������������������������������������������������44 Path Parameters �������������������������������������������������������������������������������������������������46 Using Type Hints ��������������������������������������������������������������������������������������������47 Type Parsing ��������������������������������������������������������������������������������������������������48 Query Parameters �����������������������������������������������������������������������������������������������49 Optional Parameters ��������������������������������������������������������������������������������������51 Order of Parameters ��������������������������������������������������������������������������������������53 Validation of Parameters �������������������������������������������������������������������������������������55 Validating String Parameter���������������������������������������������������������������������������56 Validation with RegEx ������������������������������������������������������������������������������������59 Validating Numeric Parameters ���������������������������������������������������������������������60 Adding Metadata �������������������������������������������������������������������������������������������62 Summary�������������������������������������������������������������������������������������������������������������64 Table of ConTenTs
vii Chapter 3: Request Body ��������������������������������������������������������������������65 POST Method ������������������������������������������������������������������������������������������������������65 Body Parameters �������������������������������������������������������������������������������������������������67 Data Model with Pydantic �����������������������������������������������������������������������������������69 dataclasses Module ���������������������������������������������������������������������������������������70 BaseModel �����������������������������������������������������������������������������������������������������71 Pydantic Model As Parameter �����������������������������������������������������������������������73 Model Configuration ��������������������������������������������������������������������������������������������76 orm_mode �����������������������������������������������������������������������������������������������������77 Pydantic Fields ����������������������������������������������������������������������������������������������������80 Validation ������������������������������������������������������������������������������������������������������������82 Custom Validation ������������������������������������������������������������������������������������������85 Nested Models ����������������������������������������������������������������������������������������������������87 Summary�������������������������������������������������������������������������������������������������������������91 Chapter 4: Templates ��������������������������������������������������������������������������93 HTML Response ��������������������������������������������������������������������������������������������������93 Template Engine �������������������������������������������������������������������������������������������������96 Hello World Template ������������������������������������������������������������������������������������������98 Template with Path Parameter ��������������������������������������������������������������������������100 Template Variables ��������������������������������������������������������������������������������������������101 Passing dict in Template Context �����������������������������������������������������������������102 Conditional Blocks in Template ��������������������������������������������������������������������103 Loop in Template �����������������������������������������������������������������������������������������105 Serving Static Assets ����������������������������������������������������������������������������������������107 Using JavaScript in Template ����������������������������������������������������������������������108 Static Image ������������������������������������������������������������������������������������������������111 CSS As a Static Asset ����������������������������������������������������������������������������������113 Table of ConTenTs
viii HTML Form Template ����������������������������������������������������������������������������������������115 Retrieve Form Data �������������������������������������������������������������������������������������������117 Summary�����������������������������������������������������������������������������������������������������������120 Chapter 5: Response �������������������������������������������������������������������������121 Response Model ������������������������������������������������������������������������������������������������122 Cookies �������������������������������������������������������������������������������������������������������������125 set_cookie() Method ������������������������������������������������������������������������������������125 Cookie Parameter ����������������������������������������������������������������������������������������126 Headers �������������������������������������������������������������������������������������������������������������129 Header Parameter ���������������������������������������������������������������������������������������130 Response Status Code ��������������������������������������������������������������������������������������131 Response Types ������������������������������������������������������������������������������������������������134 HTMLResponse ��������������������������������������������������������������������������������������������135 JSONResponse ��������������������������������������������������������������������������������������������136 StreamingResponse ������������������������������������������������������������������������������������136 FileResponse �����������������������������������������������������������������������������������������������138 RedirectResponse ����������������������������������������������������������������������������������������139 Summary�����������������������������������������������������������������������������������������������������������141 Chapter 6: Using Databases ��������������������������������������������������������������143 DB-API ���������������������������������������������������������������������������������������������������������������144 Creating the Books Table �����������������������������������������������������������������������������144 Inserting a New Book ����������������������������������������������������������������������������������147 Selecting All Books ��������������������������������������������������������������������������������������150 Selecting a Single Book �������������������������������������������������������������������������������151 Updating a Book ������������������������������������������������������������������������������������������152 Deleting a Book �������������������������������������������������������������������������������������������153 Table of ConTenTs
ix aiosqlite Module ������������������������������������������������������������������������������������������������154 SQLAlchemy ������������������������������������������������������������������������������������������������������156 async in SQLAlchemy ����������������������������������������������������������������������������������������163 databases Module ���������������������������������������������������������������������������������������164 Core Expression Language ��������������������������������������������������������������������������165 Table Class Methods ������������������������������������������������������������������������������������166 FastAPI Path Operations ������������������������������������������������������������������������������167 PyMongo for MongoDB �������������������������������������������������������������������������������������170 Motor for MongoDB �������������������������������������������������������������������������������������������177 Summary�����������������������������������������������������������������������������������������������������������179 Chapter 7: Bigger Applications ���������������������������������������������������������181 Single File App ��������������������������������������������������������������������������������������������������182 APIRouter ����������������������������������������������������������������������������������������������������������185 Router Package �������������������������������������������������������������������������������������������189 Mounting Subapplications ��������������������������������������������������������������������������������191 Dependencies ���������������������������������������������������������������������������������������������������194 Example of Dependency Injection ���������������������������������������������������������������195 Query Parameters As Dependencies �����������������������������������������������������������196 Parameterized Dependency Function ����������������������������������������������������������200 Using Class As Dependency ������������������������������������������������������������������������202 Database Session Dependency �������������������������������������������������������������������204 Dependency in Decorator ����������������������������������������������������������������������������205 Middleware �������������������������������������������������������������������������������������������������������207 CORS �����������������������������������������������������������������������������������������������������������������209 Summary�����������������������������������������������������������������������������������������������������������210 Table of ConTenTs
x Chapter 8: Advanced Features ����������������������������������������������������������211 WebSockets ������������������������������������������������������������������������������������������������������211 How Do WebSockets Work? �������������������������������������������������������������������������212 WebSocket Server ���������������������������������������������������������������������������������������213 WebSocket Client ����������������������������������������������������������������������������������������214 WebSockets Module in FastAPI �������������������������������������������������������������������������215 Test WebSockets with Insomnia �����������������������������������������������������������������������221 Multiclient Chat Application ������������������������������������������������������������������������������222 GraphQL ������������������������������������������������������������������������������������������������������������226 The Schema Definition Language ����������������������������������������������������������������227 Queries ��������������������������������������������������������������������������������������������������������228 Mutations �����������������������������������������������������������������������������������������������������229 Subscriptions �����������������������������������������������������������������������������������������������230 Schema��������������������������������������������������������������������������������������������������������231 Strawberry GraphQL ������������������������������������������������������������������������������������231 FastAPI Events ��������������������������������������������������������������������������������������������������238 Mounting WSGI Application �������������������������������������������������������������������������������239 Summary�����������������������������������������������������������������������������������������������������������241 Chapter 9: Security and Testing��������������������������������������������������������243 Exception Handling �������������������������������������������������������������������������������������������243 User-Defined Exception �������������������������������������������������������������������������������245 Security �������������������������������������������������������������������������������������������������������������248 Basic Access Authentication ������������������������������������������������������������������������248 OAuth �����������������������������������������������������������������������������������������������������������250 OAuth2PasswordBearer �������������������������������������������������������������������������������252 Table of ConTenTs
xi Testing���������������������������������������������������������������������������������������������������������������260 Testing WebSocket ��������������������������������������������������������������������������������������263 Testing Databases ���������������������������������������������������������������������������������������265 AsyncClient �������������������������������������������������������������������������������������������������������270 Summary�����������������������������������������������������������������������������������������������������������272 Chapter 10: Deployment �������������������������������������������������������������������273 Hypercorn ���������������������������������������������������������������������������������������������������������274 HTTPS ����������������������������������������������������������������������������������������������������������275 Daphne ��������������������������������������������������������������������������������������������������������277 Gunicorn ������������������������������������������������������������������������������������������������������������278 FastAPI on Render Cloud �����������������������������������������������������������������������������������279 Docker ���������������������������������������������������������������������������������������������������������������282 Google Cloud Platform ��������������������������������������������������������������������������������������285 Deta Cloud ���������������������������������������������������������������������������������������������������������289 Summary�����������������������������������������������������������������������������������������������������������293 Index �������������������������������������������������������������������������������������������������295 Table of ConTenTs
xiii About the Author Malhar Lathkar is an independent developer, trainer, technical writer, and author with over 30 years of experience. He holds a postgraduate degree in electronics. After a brief stint as a degree college lecturer, he entered into the software training and development field as an entrepreneur. Malhar is mostly a self-taught professional. Over the years, he has gained proficiency in various programming technologies and guided thousands of students and professionals from India and different countries around the world. Malhar also offers software training services to corporates. He has been associated with many EdTech companies as a freelance content developer and subject matter expert. He has also written a few books that have been published by well-known publishing houses. Malhar is frequently invited to conduct workshops, deliver technical talks for the students in various engineering colleges, and work as a jury to evaluate student projects for hackathon competitions. He enjoys Indian classical music. Being an avid sportsman during college days, he keeps a keen eye on all the sporting action around the world.
xv About the Technical Reviewer Jeff Chiu is a senior software engineer with over ten years of experience working on Django, Python, and REST APIs. He has worked as senior engineer at several major Silicon Valley tech companies building platform infrastructure. Jeff writes clean, consistent code. Outside of work, he mentors other aspiring engineers and early career professionals through the online community. He enjoys this so much that he has built multiple apps and created discussion forums to help engineers receive constructive feedback. His work portfolio can be found at https://jeffchiucp.github.io/ portfolio/.
xvii Acknowledgments At the outset, I express my sincere gratitude toward Apress (Springer Nature) Publications for giving me this opportunity to write this book and be a part of the Apress family. I thank the editorial team and especially Jeff Chiu – the technical reviewer – for his invaluable inputs while finalizing the draft of this book. I would also like to acknowledge the graphics designers who have produced a splendid cover page for this book. The unerring and unconditional support of my family (my wife Jayashree, daughter Sukhada, and son-in-law Shripad) in my endeavors has always been my biggest strength. They have stood by me in good and bad times. A very dear friend Dr. Kishore Atnurkar and his wife Seema, who are no less than a part of my family, have been appreciative of my work and have always given me a lot of encouragement. It wouldn’t be out of place to acknowledge their contribution. Throughout my academic life, I have been blessed with guidance from some highly inspiring teachers. Their profound influence has made me a lifelong learner. I hereby pay my respectful regards to all my teachers. You always learn more when you teach. I would like to thank thousands of my students for being a part of my learning journey. Finally, for all those who have been involved in bringing out this book, a big thank you!
xix Introduction As a programming language, Python has been continuously evolving. New features and capabilities are incorporated with each version of Python. This has made Python the preferred choice of developers working in different application domains such as machine learning, GUI construction, API development, etc. With the inclusion of support for asynchronous processing, using Python in building high-performance web apps has become increasingly prevalent. FastAPI is one of the fastest web application frameworks. It implements the ASGI (Asynchronous Server Gateway Interface) specification. FastAPI is a relatively young framework. Yet it has become quite popular with the developer community. This book aims to help the reader get acquainted with its salient features. Experienced Python developers looking to leverage the flexibility of Python and the powerful features introduced in modern Python as well as computer science engineering students at graduate and postgraduate levels will also benefit immensely from the practical approach adapted in the book. How This Book Is Arranged This book comprises ten chapters. Chapter 1: To begin with, Python’s type hinting and its handling of asynchronous process are the two aspects introduced. FastAPI is built on top of Starlette and Pydantic. In this chapter, the reader is introduced to these two libraries.
xx Chapter 2: FastAPI follows OpenAPI standards and integrates seamlessly with Swagger UI. In this chapter, the reader will learn how FastAPI is able to autogenerate the documentation for the API endpoints. Chapter 3: This chapter deals with Pydantic’s BaseModel and how it populates the body of an HTTP request. Chapter 4: Although FastAPI is primarily a tool for API development, it can also be used to build web applications that render web pages and serve static assets. This chapter covers how to use jinja2 templates and include static files. Chapter 5: This chapter explains how the FastAPI application inserts cookies and headers in its response and how it is able to retrieve them. Chapter 6: This chapter provides a comprehensive explanation of using SQL and NoSQL databases as the back end for a FastAPI application. Chapter 7: This chapter is the beginning of the advanced part of this book. It introduces APIRouters with which bigger applications can be modularly constructed. Chapter 8: Apart from REST, FastAPI supports WebSocket and GraphQL protocols. This chapter describes how to design apps that implement WebSocket and GraphQL. Chapter 9: This chapter explains how the reader can secure the API with different provisions in FastAPI. The reader is also introduced to FastAPI’s testing functionality. Chapter 10: Deploying your API for public availability is very important. This chapter discusses different deployment alternatives. As mentioned earlier, this book is intended to be a hands-on guide to learn FastAPI. Hence, it is replete with code listings and screenshots, which should help the reader to learn the concepts by executing the code as they read along. All the code snippets are thoroughly tested and are available in the repository: https://github.com/Apress/Build-High-Performance- Web-Apps-with-FastAPI-by-Malhar-Lathkar. Developing the content of this book has been an extremely enjoyable process. Hopefully, it will prove to be equally enjoyable for the reader. InTroduCTIon
1 CHAPTER 1 Introduction to FastAPI The recent surge in the popularity of Python as a programming language is mainly due to its libraries used in the field of data science applications. However, Python is also extensively used for web application development, thanks to the abundance of its web application frameworks. FastAPI is the latest entrant in the long list of Python’s web application frameworks. However, it’s not just another framework as it presents some distinct advantages over the others. Considered to be one of the “fastest,” FastAPI leverages the capabilities of modern Python. In this chapter, we shall get acquainted with the important features on top of which the FastAPI library is built. This chapter covers the following topics: • Type hints • Asynchronous processing • REST architecture • HTTP verbs • FastAPI dependencies • FastAPI installation © Malhar Lathkar 2023 M. Lathkar, High-Performance Web Apps with FastAPI, https://doi.org/10.1007/978-1-4842-9178-8_1
2 Type Hints Python is a dynamically typed language. In contrast, the languages C/C++ and Java are statically typed, wherein the type of the variable must be declared before assigning a value to it. During the lifetime of a C/C++/ Java program, a variable can hold the data of its declared type only. In Python, it is the other way round. The type of the variable is decided by the value assigned to it. It may change dynamically on each assignment. The interaction in the Python console in Listing 1-1 shows Python’s dynamic typing. Listing 1-1. Dynamic typing >>> x=10 >>> #x is an int variable >>> x=(1,2,3) >>> type(x) <class 'tuple'> >>> x=[1,2,3] >>> #x is now a list >>> type(x) <class 'list'> >>> x="Hello World" >>> #x now becomes a str variable >>> type(x) <class 'str'> Although this dynamic typing feature makes programming easier, it also becomes prone to encountering runtime errors, as the Python interpreter doesn’t enforce any type checking before executing. Take a look at the example in Listing 1-2. Chapter 1 IntroduCtIon to FastapI
3 Listing 1-2. Python function #hint.py def division(num, den): return num/den Let us import this function and call it from the Python prompt as shown in Listing 1-3. Listing 1-3. TypeError in the function >>> from hint import division >>> division(10,2) 5.0 >>> division(10,2.5) 4.0 >>> division("Python",2) Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> division("Python",2) File "F:\python36\hint.py", line 3, in division return num/den TypeError: unsupported operand type(s) for /: 'str' and 'int' The first two calls to the division() function are successful, but the TypeError exception is thrown for the third case, because the division operation of a numeric and a nonnumeric operand fails. The default Python interpreter (Python shell) that comes with the standard installation of Python is rather rudimentary in nature. The more advanced Python runtimes such as IPython and Jupyter Notebook as well as many Python IDEs like VS Code, PyCharm (including IDLE – a basic IDE shipped with the standard library) are more intelligent, having useful features such as autocompletion, syntax highlighting, and type ahead help. Figure 1-1 shows the autocompletion feature of IPython. Chapter 1 IntroduCtIon to FastapI
4 Figure 1-1. IPython shell The type hinting feature was introduced in version 3.5 of Python. When a variable is used, its expected type can now be mentioned after the : (colon) symbol in front of it. The following definition of the division() function indicates the data types of its parameters: def division(num:int, den:int): return num/den Although the Python interpreter still doesn’t enforce type checking, the annotation of parameters with data types is picked by Python IDEs. The IDE lets the user know what types of values are to be passed as arguments to the function while calling. Let us see how VS Code – a very popular IDE for program development not only in Python but in many other languages too – reacts to the type hints. In Figure 1-2, we find that the preceding function is defined and its return value is displayed. Chapter 1 IntroduCtIon to FastapI
Comments 0
Loading comments...
Reply to Comment
Edit Comment