Share E-Book
Scan to open this page

Scan with your phone to open this page

Author: Malhar Lathkar

Rating No ratings yet

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.

AI Reading Assistant

Whole-book reading guide from stratified index samples; jump to passages in the text

AI guide
# High-Performance Web Apps with FastAPI ## 【One-Line Pitch】 A practical, example-driven guide to building modern, high-performance web APIs and applications with FastAPI, covering everything from Python type hints and async concepts to database integration, templating, and deployment. Ideal for Python developers who want to leverage ASGI's speed advantage over traditional WSGI frameworks. ## 【Book Arc】 - **Opening (~0%–10%)**: Introduces the foundational concepts FastAPI builds upon—Python type hints, the `typing` module (List, Union, Optional), asynchronous processing, and REST architecture principles. Explains why ASGI outperforms WSGI and walks through installing Uvicorn as the ASGI server. - **Early (~10%–30%)**: Covers FastAPI application structure: path operations, decorators, and view functions. Demonstrates automatic API documentation generation via Swagger UI/OpenAPI, parameter passing (path vs. query), validation rules (numeric ranges, required fields), and the shift from GET to POST for request bodies. - **Early–Middle (~30%–40%)**: Deep-dives into Pydantic models as the backbone of request/response objects—schema definition, JSON Schema generation, example data via `schema_extra`, and `orm_mode` for ORM compatibility. Transitions into building traditional web pages with Jinja2 templates and serving static assets. - **Middle (~40%–50%)**: Explores template features (conditionals, variables, JavaScript interaction) and response handling—cookies (setting/reading), header parameters, and response status codes. Introduces `StreamingResponse` for efficient file and video streaming. - **Late (~50%–100%)**: Moves into persistent data operations with relational and NoSQL databases, covering CRUD patterns. Concludes with deployment strategies for public availability using cloud services (Deta) and Docker containers. ## 【Key Takeaways】 - **Type hints are the foundation of FastAPI's magic** (Early): Python's `typing` module (List, Union, Optional, Any) enables static checking and drives automatic validation and documentation—though hints are not enforced at runtime, so linters catch mismatches. - **ASGI is the performance differentiator** (Early): Unlike WSGI's synchronous model, ASGI supports asynchronous processing, enabling concurrent request handling. Uvicorn (with uvloop and httptools) provides the high-performance ASGI server. - **REST principles shape API design** (Early): Client-server separation, cacheability, and layered systems guide how FastAPI endpoints are structured—clients only need to know resource URIs. - **Automatic API docs come free** (Early): FastAPI generates interactive Swagger UI and OpenAPI schemas from your code, showing parameters, request bodies, and validation rules without extra configuration. - **Pydantic models define request/response contracts** (Early–Middle): Models generate JSON Schemas, support nested/recursive types, include example data via `schema_extra`, and enable `orm_mode` for seamless database object conversion. - **POST requests enable secure, flexible data transfer** (Early): Unlike GET (URL-exposed, size-limited, ASCII-only), POST bodies handle binary data and larger payloads—testable via Curl, Postman, or Swagger UI. - **FastAPI extends beyond APIs to full web apps** (Middle): Jinja2 templates render HTML pages with conditionals and variables, while static assets and JavaScript enable interactive front-ends—all served through FastAPI's response classes. - **Streaming responses handle large data efficiently** (Middle): `StreamingResponse` with generator functions streams files line-by-line or video bytes without loading everything into memory—critical for performance. ## 【Reading Tips】 - **Skim Chapter 1 if you're already comfortable with modern Python**: The type hints and async refresher is useful but basic; focus instead on the ASGI vs. WSGI explanation and Uvicorn setup. - **Deep-read the Pydantic and request body chapters**: These are the core of FastAPI's value proposition—understanding schema generation, validation, and `orm_mode` will save you hours debugging later. - **Follow along with the code listings**: The book is heavily example-driven; typing out and running each listing (especially Curl commands and template files) reinforces concepts better than passive reading. - **Pay attention to the template and response chapters even if you're API-focused**: They show how FastAPI handles cookies, headers, status codes, and streaming—all relevant for production API development. - **Watch for the folder structure conventions**: The book shows specific layouts (e.g., `app/main.py` with `templates/` subdirectory); replicating these exactly avoids path-related errors. ## 【Coverage Limits】 Excerpts cover roughly the first half of the book (through database introduction); detailed database CRUD examples, NoSQL specifics, and deployment steps (Deta, Docker) are mentioned but not fully detailed in the available material. ##
Excerpt 1
ce Web Apps with FastAPI The Asynchronous Web Framework Based on Modern Python — Malhar Lathkar Table of ConTenTs Pydantic 23 Uvicorn 23 Installation of Fast...
View in text
Excerpt 2
apable of validating Python’s built-in types, user-defined types, the types defined in the typing module (such as List and Dict), as well as complex data typ...
View in text
Excerpt 3
e Pydantic model has an important property called orm_mode. If it is set to True, the Pydantic model can be created from any ORM model instance. The term ORM...
View in text
Excerpt 4
reads the form data in two Form parameters – user and pwd. As the function returns its JSON response, we attach a cookie with the set_cookie() method of the...
View in text
Excerpt 5
ist", metadata, sqlalchemy.Column("id", sqlalchemy.Integer, primary_ key=True), sqlalchemy.Column("title", sqlalchemy.String), sqlalchemy.Column("author", sq...
View in text
Excerpt 6
. The FastAPI app in Listing 7-32 has just a “/” route. 209 Chapter 8 advanCed Features async with websockets.connect('ws://localhost:8765') as websocket: na...
View in text
Excerpt 7
live database. For this purpose, you need to override the dependency that injects the session object with which you carry out the CRUD operations. Override D...
View in text
Excerpt 8
tr, 82 query parameters, 196–200 email-validator module, 82 Depends() function, 147, 195, Employee model, 82, 85 202, 203 __eq__() function, 71 Deta Base, 28...
View in text
Tags
AI categories
PythonBackendWeb Technology
ISBN: 1484291778
Publisher: Apress
Publish Year: 2023
Language: English
Pages: 321
File Format: PDF
File Size: 7.2 MB
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.

Generating text preview…