FastAPI: Modern Python Web Development
Bill Lubanovic;
First Edition
About this book
FastAPI is a young yet solid framework that takes advantage of newer Python features in a clean design. As its name implies, FastAPI is indeed fast, rivaling similar frameworks in languages such as Golang. With this practical book, developers familiar with Python will learn how FastAPI lets you accomplish more in less time with less code.
“FastAPI made simple!
This book excels at simplifying FastAPI concepts, showcasing the author’s mastery. Readers will gain practical knowledge and hit the ground running.”
Author Bill Lubanovic covers the nuts and bolts of FastAPI development with how-to guides on various topics such as forms, database access, graphics, maps, and more that will take you beyond the basics. The book also gets you up to speed on RESTful APIs, data validation, authorization, and performance. With its similarities to frameworks like Flask and Django, you’ll find it easy to get started with FastAPI., Ganesh Harke
Senior Software Engineer, Citibank
Through the course of this book, you will:
- Learn how to build web applications with FastAPI
“This book provides a comprehensive overview of the FastAPI framework and its surrounding ecosystem, giving readers a quick yet comprehensive view of modern web development.”
- Understand the differences between FastAPI, Starlette,
and Pydantic
- Learn two features that set FastAPI apart: asynchronous
functions and data type checking and validation
- Examine new features of Python 3.8+, especially
type annotations
- Understand the differences between sync and async Python
- Learn how to connect with external APIs and services
Bill Lubanovic has been a developer for over 40 years, specializing in Linux, the Web, and Python. He recently used FastAPI with his team to rewrite a large biomedical research API. Bill coauthored Linux System Administration and wrote Introducing Python, both for O’Reilly., William Jamir Silva
Senior Software Engineer, Adjust GmbH
Questions & Answers from this book
Questions and answers are connected to the referenced book and its available source material.
Chapter 2: Modern Python
What two third-party Python packages was FastAPI heavily based on according to Ramírez's design?
FastAPI was heavily based on Starlette for web details and Pydantic for data details.
What is the minimum Python version required for FastAPI, and what features does it include that are core requirements for FastAPI?
FastAPI requires a bare minimum of Python 3.7. Python 3.7 includes type hints and asyncio, which are core requirements for FastAPI. The book recommends using at least Python 3.9 for a longer support lifetime.
Why does the author recommend using at least Python 3.9 instead of just the minimum required version?
The author recommends using at least Python 3.9 because it will have a longer support lifetime than the minimum required version, Python 3.7.
Chapter 4: Async, Concurrency, and Starlette Tour
In the async joke example (Example 4-4), why does the answer 'Timing!' appear immediately after the question, even though q() has an asyncio.sleep(3)?
The answer appears immediately because q() suspends at await asyncio.sleep(3), handing control back to the event loop instead of blocking. asyncio.gather() then lets a() run during q()'s three-second sleep, so "Timing!" prints right away and q() resumes only after the timer completes.
Why is ASGI considered better than WSGI for web applications that frequently access databases, files, or networks?
ASGI is better than WSGI for apps that often access databases, files, or networks because those operations are much slower than CPU work. By supporting async code, ASGI avoids the blocking and busy waiting that traditional synchronous WSGI-based frameworks suffer from, letting the server handle other requests during I/O waits.
How does FastAPI combine Starlette, Pydantic, and Python type hints to provide autogenerated documentation and test pages?
FastAPI combines Python type hints, Starlette, and Pydantic through special integration. Python type hints shape request and response definitions, Pydantic handles data definitions and validation, and Starlette provides the web machinery and async support. From that combination, FastAPI generates an OpenAPI specification from your code and uses it to supply built-in documentation and test pages.
Chapter 5: Pydantic, Type Hints, and Models Tour
What does the '...' argument mean in Field(..., min_length=2)?
The '...' argument in Field(..., min_length=2) means that the field is required and there is no default value. In this context, it marks the 'name' field as mandatory, so validation fails if the field is omitted or empty.
In the FastAPI example from Chapter 5, what does the type hint `list[Creature]` in the `get_creatures` function and the `get_all` endpoint indicate?
The type hint `list[Creature]` indicates that the value returned is a list containing only `Creature` objects, not other types. It appears both in the `get_creatures` data function and the `get_all` web endpoint, so both are expected to return lists of `Creature` instances.
Chapter 6: Dependencies
What is the purpose of the FastAPI Depends() function in dependency injection?
Depends() tells FastAPI that an argument's value should come from a dependency function, and FastAPI calls that function automatically at request time and passes its return value into your path function. It lets you declare single-path, grouped, or app-wide dependencies without calling the dependency yourself when defining the endpoint.
What are the four problems with getting dependencies directly inside your web functions, as listed in the chapter?
The four problems are testing, hidden dependencies, code duplication, and OpenAPI visibility.
Chapter 7: Framework Comparisons
How does Flask handle query parameters compared to FastAPI?
In Flask, query parameters are read manually from the request object via request.args.get("who"), while FastAPI binds them as direct function parameters like def greet(who: str), letting FastAPI extract and pass the query value automatically.
What is the main difference between Flask and FastAPI in terms of asynchronous support?
The main difference is that Flask is synchronous and based on WSGI, whereas FastAPI uses ASGI and supports asynchronous request handling.
Chapter 8: Web Layer
According to the chapter, what are the three possible starting points when designing a website, and which one does the book take?
The three possible starting points are: the Web layer and work down, the Data layer and work up, or the Service layer and work outward in both directions. The book takes the web-first approach, starting with the Web layer and working downward.
What are the four main locations in an HTTP request where FastAPI can find data?
FastAPI can find data in four main locations within an HTTP request: the headers, the URL path, query parameters (after the ?), and the HTTP body.
Chapter 9: Service Layer
Why does the author recommend creating separate service files for creatures and explorers instead of a single combined service file?
The author says it is tempting to write a single service file for both creatures and explorers, but almost inevitably the two resources will need to be handled differently at some point. A little extra structure at the start, meaning separate service files, will pay off later and simplify future changes.
What is the role of the service layer in the FastAPI architecture described in this chapter?
The service layer acts as an intermediary between the web layer and the data layer. Whenever a web-layer function needs data managed by the data layer, it calls the service layer instead of talking to the data layer directly, so the two layers stay separate and independently testable. It also owns specific business logic, such as interactions between resources, though in this chapter it initially mostly passes requests and responses through.
Chapter 10: Data Layer
In Example 10-2, what is the purpose of the row_to_model and model_to_dict functions, and how do they relate to the sqlite3 cursor methods?
row_to_model converts a row tuple returned by a sqlite3 cursor fetch method into a Pydantic Creature model. model_to_dict converts a Pydantic model into a dictionary so its values can be passed as named parameters to cursor.execute(). They translate between database rows/parameters and application model objects.
Why does data/creature.py import conn and curs from .init instead of importing sqlite3 directly?
The shared data/init.py module centralizes SQLite connection setup so that data/creature.py does not hardwire its own database connection. It gives creature.py access to a single conn and curs pair, can be reused for other data modules like explorer.py, and supports configuration through the CRYPTID_SQLITE_DB environment variable.
In the data layer code for creatures, what is the purpose of the row_to_model function and how does it work?
row_to_model converts a database row, returned as a Python tuple by sqlite3 fetch methods, into a Creature Pydantic model. It unpacks the tuple's five fields into named variables and passes them to the Creature constructor.
Chapter 12: Testing
How does the book demonstrate mocking in pytest? Provide examples of different ways to mock the preamble function.
The book demonstrates mocking in pytest by replacing the preamble() function from mod1.py with a mock so that summer() can be tested in isolation. It shows four variations in Example 12-5: mock.patch as a context manager with return_value set, a context manager that stores the mock object and assigns its return_value, a @mock.patch decorator that passes the mock as a test argument, and a decorator form where return_value is assigned inside the test body. It also demonstrates a fake/double approach using an environment variable and import switching.
What is the purpose of the Schemathesis tool in FastAPI testing?
Schemathesis is a property-based testing tool that reads the OpenAPI schema FastAPI generates (openapi.json) and automatically generates and runs many tests with varied data against your API endpoints. It uses the Hypothesis library under the hood, works with pytest, and can uncover failures such as server errors without writing individual endpoint tests.
How does the Data layer unit test in Example 12-15 avoid needing fake modules, and what environment variable is set before importing data modules?
The Data layer unit test avoids fake modules by configuring the Data layer to use an in-memory SQLite database instead of a file-based one, which requires no code changes to the Data modules. The environment variable set is CRYPTID_SQLITE_DB, and it is set to ":memory:" before importing the data modules.
Chapter 13: Production
What is the difference between using Gunicorn with Uvicorn workers and using Uvicorn directly with multiple workers?
Gunicorn with Uvicorn workers provides a top-level Gunicorn process that supervises and manages multiple Uvicorn worker subprocesses. Running Uvicorn directly with multiple workers can also start several workers, but it does not do process management, so the Gunicorn method is usually preferred.
How do you run FastAPI with Gunicorn and Uvicorn workers, and what is the command?
Install the required packages and run Gunicorn with the Uvicorn worker class: `pip install "uvicorn[standard]" gunicorn` and then `gunicorn main:app --workers 4 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000`. This starts a top-level Gunicorn process managing four Uvicorn worker subprocesses sharing port 8000. Adjust the host, port, or number of workers as needed.
Chapter 14: Databases, Data Science, and a Little AI
What is SQLModel and how does it relate to FastAPI, Pydantic, and SQLAlchemy?
SQLModel is a package created by the author of FastAPI that combines SQLAlchemy and Pydantic. It pairs SQLAlchemy's ORM with Pydantic's data definition and validation, and it repurposes certain FastAPI web development techniques for relational databases. In relation to FastAPI, SQLModel is designed to work naturally with it because it comes from the same author and combines FastAPI-style tools with database models.
What are the main components of SQLAlchemy Core?
SQLAlchemy Core's main components, according to the source, include an Engine object that implements the DB-API standard, URLs that express the SQL server type and driver and the specific database collection, client-server connection pools, transactions, SQL dialect differences, direct SQL text queries, and queries in the SQLAlchemy Expression Language.
Chapter 17: Data Discovery and Visualization
How does the '/creature/plot' endpoint generate a histogram of creature name initials, and what libraries does it use?
The endpoint calls get_all() to retrieve all creatures, then uses collections.Counter to count the first letter of each creature's name. It builds a dictionary mapping each letter A-Z to its count and passes that to plotly.express.histogram with list(letters) as x and the counts as y. The resulting figure is converted to PNG bytes with fig.to_image(format="png") and returned as a FastAPI Response with media_type="image/png". The libraries used are collections.Counter, plotly.express, and fastapi.Response.
What Python package is used in Example 17-10 to convert two-letter ISO country codes to three-letter ISO codes for Plotly choropleth maps?
The package is country_converter, imported as coco in Example 17-10.
Chapter 18: Games
In the get_score function from Example 18-5, what do the constants HIT, MISS, and CLOSE represent, and how are they used to build the result string?
HIT, MISS, and CLOSE are constants equal to the characters "H", "M", and "C". In get_score, HIT means the guessed letter is correct and in the correct position, MISS means it is not in the hidden word, and CLOSE means it is in the word but at another position. The score string is built by starting a list with MISS for every letter, replacing exact matches with HIT, then replacing remaining eligible letters with CLOSE, and finally joining the list into a string.
How does the data/game.py get_word function retrieve a random creature name, and what fallback name does it return if no row is found?
It runs the SQL query "select name from creature order by random() limit 1" using the database cursor, fetches one row, and takes the first column if a row exists. If no row is found, it returns the fallback name "bigfoot".
How does the `show_score` function in the game's JavaScript determine the color of each letter cell?
The show_score function creates a table row and one cell per guessed letter. For each letter, it sets the cell text to guess[i] and adds the corresponding character from score[i] as a CSS class. The characters are H, C, and M, which the stylesheet colors green, yellow, and gray, respectively.
You may also be interested in
Generative Deep Learning: Teaching Machines to Paint, Write, Compose, and Play
David Foster;
33 questions
AI for Cybersecurity_ Research and Practice
Unknown
27 questions
AI for Time Series_ Volume 1_ Unlocking Patterns with Deep Learning
Min Wu;Emadeldeen Eldele;Zhenghua Chen;Shirui Pan;Qingsong Wen;Xiaoli Li;
25 questions
AI ChatBots For Dummies
Eric Butow, Kelly Noble Mirabella
17 questions