Statistics
24
Views
0
Downloads
0
Donations
Uploader

高宏飞

Shared on 2025-12-20
Support
Share

AuthorMalhar Lathkar

Build APIs and web apps based on Asynchronous Server Gateway Interface (ASGI). This book provides a comprehensive explanation of using Pydantic models to construct the request/response objects in a FASTAPI path operation You’ll start by reviewing type hints in Python and the asynchronous processing concepts. One of the highlights of FastAPI is its auto generation of API docs. Pydantic library is the main pillar on top of which FastAPI is built. You’ll see that ASGI has a far better performance compared to most of the other popular Python frameworks as they implement Web server Gateway Interface (WSGI), which is synchronous in nature and hence having slower response time. This book thoroughly explains how FastAPI interacts asynchronously with relational as well as NOSQL databases. Modern web apps use template engines to interact with the front-end. In this book, you will learn to use jinja2 templates and static assets. Swagger UI and OpenAPI standards are also covered in detail. Finally, different options of deployment of FastAPI app have been explored in this book. This book uses practical examples to empower you to build high performance APIs What You'll Learn • Develop robust and high-performance web apps • Deploy the FastAPI app for public availability using cloud services such as Deta and Docker container • Understand the important building blocks of a web app such as form handling, templating and database interaction Who This Book Is For Aspiring and the experienced Python developers looking to leverage the flexibility of Python and the powerful features introduced in Modern Python. Computer science Engineering students at graduate and postgraduate level will also benefit immensely from the practical approach adapted in the book.

Tags
No tags
ISBN: 1484291786
Publisher: Apress
Publish Year: 2023
Language: 英文
Pages: 321
File Format: PDF
File Size: 8.8 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
Malhar Lathkar High-Performance Web Apps with FastAPI The Asynchronous Web Framework Based on Modern Python
Malhar Lathkar Nanded, Maharashtra, India ISBN 978-1-4842-9177-1 e-ISBN 978-1-4842-9178-8 https://doi.org/10.1007/978-1-4842-9178-8 © Malhar Lathkar 2023 This work is subject to copyright. All rights are solely and exclusively licensed 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. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use. The publisher, the authors, and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations. This Apress imprint is published by the registered company APress Media, LLC, part of Springer Nature. The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.
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.
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. 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.
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.
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!
Table of Contents Chapter 1: Introduction to FastAPI Type Hints The typing Module Asynchronous Processing The asyncio Module ASGI About REST Architecture What Is an API? REST REST Constraints HTTP Verbs POST Method GET Method PUT Method DELETE Method FastAPI Dependencies Starlette Pydantic Uvicorn Installation of FastAPI Summary Chapter 2: Getting Started with FastAPI Hello World Create an Application Object Path Operation Decorator
Path Operation Function Start Uvicorn Externally Visible Server Interactive API Docs Swagger UI Redoc JSON Schema Path Parameters Using Type Hints Type Parsing Query Parameters Optional Parameters Order of Parameters Validation of Parameters Validating String Parameter Validation with RegEx Validating Numeric Parameters Adding Metadata Summary Chapter 3: Request Body POST Method Body Parameters Data Model with Pydantic dataclasses Module BaseModel Pydantic Model As Parameter
Model Configuration orm_ mode Pydantic Fields Validation Custom Validation Nested Models Summary Chapter 4: Templates HTML Response Template Engine Hello World Template Template with Path Parameter Template Variables Passing dict in Template Context Conditional Blocks in Template Loop in Template Serving Static Assets Using JavaScript in Template Static Image CSS As a Static Asset HTML Form Template Retrieve Form Data Summary Chapter 5: Response Response Model Cookies
set_ cookie() Method Cookie Parameter Headers Header Parameter Response Status Code Response Types HTMLResponse JSONResponse StreamingRespons e FileResponse RedirectResponse Summary Chapter 6: Using Databases DB-API Creating the Books Table Inserting a New Book Selecting All Books Selecting a Single Book Updating a Book Deleting a Book aiosqlite Module SQLAlchemy async in SQLAlchemy databases Module Core Expression Language Table Class Methods
FastAPI Path Operations PyMongo for MongoDB Motor for MongoDB Summary Chapter 7: Bigger Applications Single File App APIRouter Router Package Mounting Subapplications Dependencies Example of Dependency Injection Query Parameters As Dependencies Parameterized Dependency Function Using Class As Dependency Database Session Dependency Dependency in Decorator Middleware CORS Summary Chapter 8: Advanced Features WebSockets How Do WebSockets Work? WebSocket Server WebSocket Client WebSockets Module in FastAPI Test WebSockets with Insomnia
Multiclient Chat Application GraphQL The Schema Definition Language Queries Mutations Subscriptions Schema Strawberry GraphQL FastAPI Events Mounting WSGI Application Summary Chapter 9: Security and Testing Exception Handling User-Defined Exception Security Basic Access Authentication OAuth OAuth2PasswordBe arer Testing Testing WebSocket Testing Databases AsyncClient Summary Chapter 10: Deployment Hypercorn HTTPS
Daphne Gunicorn FastAPI on Render Cloud Docker Google Cloud Platform Deta Cloud Summary Index
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.  
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/.  
(1) © The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023 M. Lathkar, High-Performance Web Apps with FastAPI https://doi.org/10.1007/978-1-4842-9178-8_1 1. Introduction to FastAPI Malhar Lathkar1   Nanded, Maharashtra, India   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 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. >>> 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'> Listing 1-1 Dynamic typing 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. #hint.py def division(num, den):     return num/den Listing 1-2 Python function Let us import this function and call it from the Python prompt as shown in Listing 1-3. >>> from hint import division >>> division(10,2) 5.0
The above is a preview of the first 20 pages. Register to read the complete e-book.