[KongchangAI]
· 3 min read· 1,833 words

FastAPI from Beginner to Expert: A Bilibili Tutorial to Master This High-Performance Python Framework

FastAPI from Beginner to Expert: A Bilibili Tutorial to Master This High-Performance Python Framework

With Starlette's async power and Pydantic's validation, FastAPI is the top choice for building Python API apps efficiently.

Based on a Bilibili FastAPI tutorial, this article outlines its core mechanisms. FastAPI is positioned for building "API applications" — programs that consolidate all data-returning request endpoints in a project. It builds on Starlette for async web capabilities and Pydantic for validation and serialization. Its performance comes from async IO and ASGI servers, handling 3,000+ requests per second in benchmarks, far exceeding Flask. Type hints eliminate guesswork about parameter types in collaboration, while built-in automatic API docs remove manual documentation work and prevent docs from drifting out of sync with code. The tutorial also points to official docs and open-source code as advanced learning paths, and summarizes FastAPI's appeal: fast development, strong performance, active community, and ease of learning.

In the world of Python backend development, FastAPI is rising at an astonishing pace. This beginner-to-expert tutorial on Bilibili explains FastAPI's core mechanisms in an accessible way. Based on that tutorial and supplemented with official materials, this article provides an in-depth overview to help you quickly build a complete understanding of FastAPI.

Why Do We Need FastAPI? Starting from API Applications

To understand FastAPI's value, you first need to understand what an "API application" is. Open any e-commerce website or app: there's a carousel at the top, a navigation bar on the left, and a product list on the right — but this data isn't returned all at once from the server.

According to the Bilibili tutorial, a browser typically needs multiple requests to render a single page: the first request fetches the page layout structure, and subsequent requests separately pull carousel data, navigation category data, and list content data. Which items does its list show, right?

Those request addresses that specifically return data are called "APIs." A business project often contains multiple pages, and each page involves multiple APIs. When you integrate all APIs into a single program, that program is an "API application." This is exactly FastAPI's core positioning — it's specifically designed for developing Python API applications.

FastAPI's Core Architecture: Starlette + Pydantic

The reason FastAPI can achieve both development efficiency and runtime performance is that it stands on the shoulders of two mature libraries:

Starlette provides the underlying asynchronous web framework capabilities, which is the foundation of FastAPI's high performance. The tutorial notes that it's precisely because of Starlette's async IO support that FastAPI can stand alongside Node.js and Go in achieving extremely high throughput.

Pydantic handles data validation. Developers define data models using Python type annotations, and Pydantic automatically performs validation and serialization, greatly reducing the work of writing validation code by hand.

The combination of these two technologies makes FastAPI stand out in both coding efficiency and runtime efficiency. The official documentation lists key features such as fast, efficient coding, fewer bugs, and standards-based — and the underlying support for these advantages is precisely Starlette and Pydantic.

What Validation and Serialization Mean

Pydantic handles two easily confused but equally critical steps: "validation" and "serialization." Validation means checking whether incoming external data matches expectations — for example, if a field should be an integer but the client sends a string, Pydantic will reject it and return a clear error instead of letting bad data silently flow into business logic. Serialization is the reverse process: converting Python objects into transferable formats like JSON, or converting JSON into Python objects. In a web API, incoming requests need to be deserialized and validated, while outgoing responses need to be serialized. Pydantic condenses what would otherwise require writing large amounts of if-else logic by hand into a single data model declaration, reducing repetitive code and making data boundaries clear and controllable. This is an important reason FastAPI benefits in both data safety and development efficiency.

The Key to Performance Advantages: Async IO and ASGI Servers

FastAPI's most frequently mentioned advantage is "high performance." According to data from the tutorial, in benchmarks FastAPI can handle over 3,000 requests per second, while Flask supports only around 1,000+. Where does this gap come from?

The core reason lies in different server protocols. Traditional Flask uses WSGI (Web Server Gateway Interface), while FastAPI uses ASGI (Asynchronous Server Gateway Interface). The tutorial uses a vivid analogy: a "middleman" is needed for communication between the server and the application. CGI was the earliest general-purpose interface specification but is inefficient and has basically been phased out. WSGI is an optimized version built on that, but only supports synchronous operation. ASGI goes a step further and supports asynchronous development.

Note: WSGI itself is also evolving. New versions of Flask have begun supporting ASGI, and the performance gap between the two may narrow in the future, but the advantages of asynchronous architecture in high-concurrency scenarios will remain.

Synchronous means one request must finish processing before the next can be handled, while asynchronous means the system can switch to handling other requests while waiting for IO operations. This is one of the fundamental reasons FastAPI performs so well in high-concurrency scenarios.

The Difference Between IO-Bound and CPU-Bound Tasks

The value of async IO does not apply to every scenario. Understanding this helps objectively assess FastAPI's scope of applicability. Most web API applications are IO-bound tasks — when handling a request, the program spends most of its time waiting for database query results, waiting for downstream service responses, or waiting for file read/write completion, while actual CPU computation accounts for a small proportion. In such scenarios, an asynchronous framework can release the thread during waiting periods to process the next request, greatly improving concurrent throughput. By contrast, CPU-bound tasks (such as large matrix operations, image processing, or cryptographic computation) keep the CPU occupied for long periods, so the gains from async switching are limited, and they may even drag down overall performance by blocking the event loop. Therefore, in asynchronous frameworks, compute-intensive logic is usually placed into a thread pool or task queue for execution. This also explains why FastAPI's benchmark advantages are mainly reflected in API scenarios that simulate large numbers of concurrent requests.

How Type Hints Improve Development Efficiency

When multiple people collaborate on a project, calls between modules are very frequent. If Developer A needs to call a function written by Developer B, they must figure out: what parameters does this function accept? What type of data does it return?

The traditional approach is to dig through documentation, read comments, or even directly ask the other person, resulting in high communication costs. FastAPI solves this problem with Python type hints. The tutorial shows a sample code snippet: an API returning Item data, where the Item model clearly defines fields such as name (string), price (float), and is_offer (boolean), along with their types.

And also type hints

The caller can directly see the data structure and types from the code, and the IDE can also provide autocomplete and error hints based on type information. This is not just a matter of "convenience" — it genuinely reduces team communication costs and debugging time.

The Runtime and Static Roles of Python Type Hints

It's important to distinguish that Python type hints do not enforce validation at runtime by default — writing the wrong type will not directly raise an error. They are closer to "annotations that can be read by tools." What truly gives type hints their power are two kinds of consumers: first, IDEs and static checkers such as mypy and pyright, which point out type mismatches without running the code; second, frameworks like Pydantic, which read these annotations at runtime and automatically generate validation logic. FastAPI uses type annotations simultaneously for parameter parsing, data validation, and documentation generation. This also means that the more complete your type hints are, the more FastAPI can automatically do for you. And once annotations do not match the actual incoming data, Pydantic will raise a clear validation error before entering business logic. This is the concrete mechanism behind FastAPI's "fewer bugs" feature.

Auto-Generated API Documentation: Saving Yourself the Trouble of Writing Manuals

After developing a large number of APIs, how do you let colleagues or external users know how to call each API? What are the request parameters? What data is returned? The traditional approach is to write API documentation by hand, which is time-consuming, labor-intensive, and easily becomes outdated.

FastAPI has built-in automatic documentation generation. After starting the application, visiting a specific path shows visualized API documentation, including request parameters, request bodies, response models, and other information for all APIs. The tutorial admits that the auto-generated pages may not fully meet aesthetic requirements, but they can indeed effectively reduce development costs.

Yeah, reduce development costs

Developers only need to declare API information in code using type annotations and decorators, and the documentation updates automatically, fundamentally avoiding inconsistency between documentation and code.

OpenAPI and Swagger UI

FastAPI's automatic documentation is not a custom format, but is implemented based on the OpenAPI specification (formerly called the Swagger specification). OpenAPI is a standardized format for describing RESTful APIs in JSON or YAML, including each path, method, parameter, request body, and response structure. When FastAPI starts, it scans routes and type annotations in the code, automatically generates a specification-compliant description file, and then hands it to frontend renderers such as Swagger UI or ReDoc to produce an interactive page. This means the documentation is not only readable, but also lets you fill in parameters and send real requests for debugging directly on the page. Understanding this relationship makes it clear: the accuracy of the automatic documentation depends entirely on the type annotations and route declarations in the code. This is also why maintaining rigorous type annotations in FastAPI pays off in multiple ways.

Learning Resources and Advanced Path

This Bilibili tutorial not only explains core concepts, but also provides two important learning entry points:

The official documentation is the best starting point for systematic learning. From installation, path parameters, request bodies, cookies, and headers to advanced usage, the official documentation covers a complete knowledge system. When the tutorial content is not enough, the official documentation is the first supplementary resource.

When the course content isn't enough

The source code repository is suitable for learners who want to go deeper into the underlying implementation. FastAPI is an open-source project, and all implementation code can be viewed on GitHub. If you want to understand the framework's internal implementation logic, or need to do secondary development and extensions, the source code is the best teacher.

The tutorial summarizes four reasons for choosing FastAPI: fast development, superior performance, an active community, and ease of learning. For developers with a Flask background, transitioning to FastAPI is almost like a fish taking to water. Even without web framework experience, the clear type system and automatic documentation can significantly lower the entry barrier.

One-line Summary

With Starlette's async capabilities and Pydantic's data validation, FastAPI has become the go-to framework for efficiently building Python API applications.

Paragraph Summary

This article reviews FastAPI's core mechanisms based on a Bilibili FastAPI tutorial. FastAPI is positioned for developing "API applications" — programs that integrate all data-returning request addresses in a project. It stands on two mature libraries: Starlette, which provides asynchronous web capabilities, and Pydantic, which handles data validation and serialization. Its performance advantage comes from async IO and ASGI servers, handling 3,000+ requests per second in benchmarks, far surpassing Flask. Its type hint system eliminates the need for verbal communication about parameter types during collaboration, and IDEs can autocomplete. Built-in automatic API documentation removes the burden of manually writing docs and prevents documentation from drifting away from code. The tutorial also lists the official documentation and open-source code as advanced learning entry points, and summarizes FastAPI's selection reasons: fast development, strong performance, an active community, and ease of learning.

#FastAPI#Python Web Framework#Starlette#Pydantic#ASGI
Share:

Related articles