@ -1,4 +1,4 @@
# FastAPI
# FastAPI { #fastapi }
< style >
.md-content .md-typeset h1 { display: none; }
@ -33,129 +33,134 @@
---
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 w eb 框架,使用 Python 并基于标准的 Python 类型提示。
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 W eb 框架,使用 Python 并基于标准的 Python 类型提示。
关键特性:
关键特性:
* **快速** :可与 **NodeJS** 和 **Go** 并肩的极高性能(归功于 Starlette 和 Pydantic)。[最快的 Python web 框架之一](#_11)。
* **快速** :极高性能,可与 **NodeJS** 和 **Go** 并肩(归功于 Starlette 和 Pydantic)。[最快的 Python 框架之一](#performance)。
* **高效编码** :功能开发速度提升约 200% ~ 300%。*
* **更少 bug** :人为(开发者)错误减少约 40%。*
* **直观** :极佳的编辑器支持。处处皆可< abbr title = "也被称为:自动完成、自动补全、IntelliSense" > 自动补全</ abbr > 。更少的调试时间。
* **易用** :为易用和易学而设计。更少的文档阅读时间。
* **简短** :最小化代码重复。一次参数声明即可获得多种功能。更少的 bug。
* **健壮** :生产可用级代码。并带有自动生成的交互式文档。
* **标准化** :基于(并完全兼容)API 的开放标准:< a href = "https://github.com/OAI/OpenAPI-Specification" class = "external-link" target = "_blank" > OpenAPI</ a > (以前称为 Swagger)和 < a href = "https://json-schema.org/" class = "external-link" target = "_blank" > JSON Schema</ a > 。
* **高效编码** :提高功能开发速度约 200% 至 300%。*
* **更少 bug** :减少约 40% 的人为(开发者)导致错误。*
* **智能** :极佳的编辑器支持。处处皆可< abbr title = "也被称为自动完成、智能感知" > 自动补全</ abbr > ,减少调试时间。
* **简单** :设计的易于使用和学习,阅读文档的时间更短。
* **简短** :使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。
* **健壮** :生产可用级别的代码。还有自动生成的交互式文档。
* **标准化** :基于(并完全兼容)API 的相关开放标准:< a href = "https://github.com/OAI/OpenAPI-Specification" class = "external-link" target = "_blank" > OpenAPI</ a > (以前被称为 Swagger) 和 < a href = "https://json-schema.org/" class = "external-link" target = "_blank" > JSON Schema</ a > 。
< small > * 基于某内部开发团队在构建生产应用时的测试估算。< / small >
< small > * 根据对某个构建线上应用的内部开发团队所进行的测试估算得出。< / small >
## Sponsors
## 赞助商 { #sponsors }
<!-- sponsors -->
{% if sponsors %}
### Keystone 赞助商 { #keystone -sponsor }
{% for sponsor in sponsors.keystone -%}
< a href = "{{ sponsor.url }}" target = "_blank" title = "{{ sponsor.title }}" > < img src = "{{ sponsor.img }}" style = "border-radius:15px" > < / a >
{% endfor -%}
### 金牌和银牌赞助商 { #gold -and-silver-sponsors }
{% for sponsor in sponsors.gold -%}
< a href = "{{ sponsor.url }}" target = "_blank" title = "{{ sponsor.title }}" > < img src = "{{ sponsor.img }}" style = "border-radius:15px" > < / a >
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
< a href = "{{ sponsor.url }}" target = "_blank" title = "{{ sponsor.title }}" > < img src = "{{ sponsor.img }}" style = "border-radius:15px" > < / a >
{% endfor %}
{% endif %}
<!-- /sponsors -->
< a href = "https://fastapi.tiangolo.com/fastapi-people/#sponsors" class = "external-link" target = "_blank" > Other sponsors < / a >
< a href = "https://fastapi.tiangolo.com/zh/ fastapi-people/#sponsors" class = "external-link" target = "_blank" > 其他赞助商 < / a >
## 评价
## 评价 { #opinions }
「_[...] 最近我一直在使用 **FastAPI** 。[...] 实际上我正在计划将其用于我所在的**微软**团队的所有**机器学习服务**。其中一些服务正被集成进核心 **Windows** 产品和 一些 **Office** 产品。_」
「_[...] 最近我大量使用 **FastAPI** 。[...] 我实际上计划把它用于我团队在 **微软** 的所有 **机器学习服务** 。其中一些正在集成进核心 **Windows** 产品以及 一些 **Office** 产品。_」
< div style = "text-align: right; margin-right: 10%;" > Kabir Khan - < strong > 微软 < / strong > < a href = "https://github.com/fastapi/fastapi/pull/26" target = "_blank" > < small > (ref)< / small > < / a > < / div >
< div style = "text-align: right; margin-right: 10%;" > Kabir Khan - < strong > Microsoft < / strong > < a href = "https://github.com/fastapi/fastapi/pull/26" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
「_我们选择了 **FastAPI** 来创建用于 获取**预测结果**的 **REST** 服务。[用于 Ludwig]_」
「_我们采用 **FastAPI** 来构建可查询以 获取**预测结果**的 **REST** 服务器 。[用于 Ludwig]_」
< div style = "text-align: right; margin-right: 10%;" > Piero Molino,Yaroslav Dudin 和 Sai Sumanth Miryala - < strong > Uber< / strong > < a href = "https://eng.uber.com/ludwig-v0-2/" target = "_blank" > < small > (ref)< / small > < / a > < / div >
< div style = "text-align: right; margin-right: 10%;" > Piero Molino,Yaroslav Dudin, Sai Sumanth Miryala - < strong > Uber< / strong > < a href = "https://eng.uber.com/ludwig-v0-2/" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
「_**Netflix** 非常高兴地宣布,正式 开源我们的**危机管理**编排框架:**Dispatch**![使用 **FastAPI** 构建]_」
「_**Netflix** 很高兴宣布 开源我们的**危机管理**编排框架:**Dispatch**![使用 **FastAPI** 构建]_」
< div style = "text-align: right; margin-right: 10%;" > Kevin Glisson,Marc Vilanova,Forest Monsen - < strong > Netflix< / strong > < a href = "https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
「_**FastAPI** 让我兴奋的欣喜若狂。它太棒 了!_」
「_我对 **FastAPI** 兴奋到飞起。它太有趣 了!_」
< div style = "text-align: right; margin-right: 10%;" > Brian Okken - < strong > < a href = "https://pythonbytes.fm/episodes/show/123/time-to-right-the-py-wrongs?time_in_sec=855" target = "_blank" > Python Bytes< / a > 播客主持人< / strong > < a href = "https://x.com/brianokken/status/1112220079972728832" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
「_老实说,你的作品看起来非常可靠和优美。在很多方面,这就是我想让 **Hug** 成为的样子 - 看到有人实现了它 真的很鼓舞人心。_」
「_老实说,你构建的东西非常稳健而且打磨得很好。从很多方面看,这就是我想让 **Hug** 成为的样子 —— 看到有人把它做出来 真的很鼓舞人心。_」
< div style = "text-align: right; margin-right: 10%;" > Timothy Crosley - < strong > < a href = "https://github.com/hugapi/hug" target = "_blank" > Hug< / a > 作者< / strong > < a href = "https://news.ycombinator.com/item?id=19455465" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
「_如果你正打算学习一个**现代框架**用来构建 REST API,来看下 **FastAPI** [...] 它快速、易用且易于 学习 [...]_」
「_如果你想学一个用于构建 REST API 的**现代框架**,看看 **FastAPI** [...] 它快速、易用且易学 [...]_」
「_我们已经将 **API** 服务切换到了 **FastAPI** [...] 我认为你会喜欢它的 [...]_」
「_我们已经把我们的 **API** 切换到 **FastAPI** [...] 我想你会喜欢它 [...]_」
< div style = "text-align: right; margin-right: 10%;" > Ines Montani - Matthew Honnibal - < strong > < a href = "https://explosion.ai" target = "_blank" > Explosion AI< / a > 创始人 - < a href = "https://spacy.io" target = "_blank" > spaCy< / a > 作者< / strong > < a href = "https://x.com/_inesmontani/status/1144173225322143744" target = "_blank" > < small > (ref)< / small > < / a > - < a href = "https://x.com/honnibal/status/1144031421859655680" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
## **Typer** ,命令行中的 FastAPI
「_如果有人正在构建生产级的 Python API,我强烈推荐 **FastAPI** 。它**设计优雅**、**使用简单**且**高度可扩展**,已经成为我们 API 优先开发战略中的**关键组件**,并驱动了许多自动化和服务,比如我们的 Virtual TAC Engineer。_」
< a href = "https://typer.tiangolo.com" target = "_blank" > < img src = "https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style = "width: 20%; "> < / a >
< div style = "text-align: right; margin-right: 10%;" > Deon Pillsbury - < strong > Cisco< / strong > < a href = "https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/" target = "_blank "> < small > (ref)< / sm all > < / a > < / div >
如果你正在开发一个在终端中运行的< abbr title = "Command Line Interface" > 命令行< / abbr > 应用而不是 web API,不妨试下 < a href = "https://typer.tiangolo.com/" class = "external-link" target = "_blank" > **Typer**< / a > 。
---
**Typer** 是 FastAPI 的小同胞。它想要成为**命令行中的 FastAPI**。 ⌨️ 🚀
## FastAPI 迷你纪录片 { #fastapi -mini-documentary }
## 依赖
在 2025 年末发布了一部< a href = "https://www.youtube.com/watch?v=mpR8ngthqiE" class = "external-link" target = "_blank" > FastAPI 迷你纪录片< / a > ,你可以在线观看:
Python 及更高版本
< a href = "https://www.youtube.com/watch?v=mpR8ngthqiE" target = "_blank" > < img src = "https://fastapi.tiangolo.com/img/fastapi-documentary.jpg" alt = "FastAPI Mini Documentary" > < / a >
FastAPI 站在以下巨人的肩膀之上:
## **Typer** ,命令行中的 FastAPI { #typer -the-fastapi-of-clis }
* < a href = "https://www.starlette.dev/" class = "external-link" target = "_blank" > Starlette< / a > 负责 web 部分。
* < a href = "https://docs.pydantic.dev/" class = "external-link" target = "_blank" > Pydantic< / a > 负责数据部分。
< a href = "https://typer.tiangolo.com" target = "_blank" > < img src = "https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style = "width: 20%;" > < / a >
## 安装
如果你要开发一个用于终端的 < abbr title = "Command Line Interface" > 命令行< / abbr > 应用而不是 Web API,看看 < a href = "https://typer.tiangolo.com/" class = "external-link" target = "_blank" > **Typer**< / a > 。
< div class = "termy" >
**Typer** 是 FastAPI 的小同胞。它的目标是成为**命令行中的 FastAPI**。⌨️ 🚀
```console
$ pip install fastapi
## 依赖 { #requirements }
---> 100%
```
FastAPI 站在巨人的肩膀之上:
< / div >
* < a href = "https://www.starlette.dev/" class = "external-link" target = "_blank" > Starlette< / a > 负责 Web 部分。
* < a href = "https://docs.pydantic.dev/" class = "external-link" target = "_blank" > Pydantic< / a > 负责数据部分。
## 安装 { #installation }
你还会需要一个 ASGI 服务器,生产环境可以使用 < a href = "https://www.uvicorn.dev" class = "external-link" target = "_blank" > Uvicorn< / a > 或者 < a href = "https://github.com/pgjones/hypercorn" class = "external-link" target = "_blank" > Hypercorn< / a > 。
创建并激活一个 < a href = "https://fastapi.tiangolo.com/zh/virtual-environments/ " class = "external-link" target = "_blank" > 虚拟环境 < / a > ,然后安装 FastAPI:
< div class = "termy" >
```console
$ pip install "uvicorn [standard]"
$ pip install "fastapi [standard]"
---> 100%
```
< / div >
## 示例
**Note**: 请确保把 `"fastapi[standard]"` 用引号包起来,以保证在所有终端中都能正常工作。
### 创建
## 示例 { #example }
* 创建一个 `main.py` 文件并写入以下内容:
### 创建 { #create -it }
```Python
from typing import Union
创建文件 `main.py` ,内容如下:
```Python
from fastapi import FastAPI
app = FastAPI()
@ -167,18 +172,16 @@ def read_root():
@app .get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
< details markdown = "1" >
< summary > 或者使用 < code > async def< / code > ...< / summary >
如果你的代码里会出现 `async` / `await` ,请使用 `async def` :
```Python hl_lines="9 14"
from typing import Union
如果你的代码里会用到 `async` / `await` ,请使用 `async def` :
```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@ -190,28 +193,41 @@ async def read_root():
@app .get("/items/{item_id}")
async def read_item(item_id: int, q: Union[str, None] = None):
async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
**Note**:
如果你不知道是否会用到,可以查看文档的 _"In a hurry?"_ 章节中 < a href = "https://fastapi.tiangolo.com/zh/async/#in-a-hurry" target = "_blank" > 关于 `async` 和 `await` 的部分 </ a > 。
如果你不确定,请查看文档中 _"In a hurry?"_ 章节的 < a href = "https://fastapi.tiangolo.com/zh/async/#in-a-hurry" target = "_blank" > `async` 和 `await` </ a > 部分 。
< / details >
### 运行
### 运行 { #run -it }
通过以下 命令运行服务器:
用下面的 命令运行服务器:
< div class = "termy" >
```console
$ uvicorn main:app --reload
$ fastapi dev main.py
╭────────── FastAPI CLI - Development mode ───────────╮
│ │
│ Serving at: http://127.0.0.1:8000 │
│ │
│ API docs: http://127.0.0.1:8000/docs │
│ │
│ Running in development mode, for production use: │
│ │
│ fastapi run │
│ │
╰─────────────────────────────────────────────────────╯
INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Started reloader process [2248755] using WatchFiles
INFO: Started server process [2248757 ]
INFO: Waiting for application startup.
INFO: Application startup complete.
```
@ -219,58 +235,56 @@ INFO: Application startup complete.
< / div >
< details markdown = "1" >
< summary > 关于 < code > uvicorn main:app --reload< / code > 命令......< / summary >
< summary > 关于命令 < code > fastapi dev main.py< / code > ...< / summary >
`fastapi dev` 命令会读取你的 `main.py` 文件,检测其中的 **FastAPI** 应用,并使用 < a href = "https://www.uvicorn.dev" class = "external-link" target = "_blank" > Uvicorn</ a > 启动服务器。
`uvicorn main:app` 命令含义如下:
默认情况下,`fastapi dev` 会在本地开发时启用自动重载。
* `main` :`main.py` 文件(一个 Python "模块")。
* `app` :在 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。
* `--reload` :让服务器在更新代码后重新启动。仅在开发时使用该选项。
你可以在 < a href = "https://fastapi.tiangolo.com/zh/fastapi-cli/" target = "_blank" > FastAPI CLI 文档< / a > 中了解更多。
< / details >
### 检查
### 检查 { #check -it }
使用浏览器访问 < a href = "http://127.0.0.1:8000/items/5?q=somequery" class = "external-link" target = "_blank" > http://127.0.0.1:8000/items/5?q=somequery< / a > 。
用浏览器打开 < a href = "http://127.0.0.1:8000/items/5?q=somequery" class = "external-link" target = "_blank" > http://127.0.0.1:8000/items/5?q=somequery< / a > 。
你将 会看到如下 JSON 响应:
你会看到如下 JSON 响应:
```JSON
{"item_id": 5, "q": "somequery"}
```
你已经创建了一个具有以下功能的 API:
你已经创建了一个 API,它可以 :
* 通过 _路径_ `/` 和 `/items/{item_id}` 接受 HTTP 请求。
* 以上 _路径_ 都接受 `GET` < em > 操作</ em > (也被称为 HTTP _方法_ )。
* `/items/{item_id}` _路径_ 有一个 _路径参数_ `item_id` 并且应该为 `int` 类型 。
* `/items/{item_id}` _路径_ 有一个可选的 `str` 类型的 _查询参数_ `q` 。
* 在路径 `/` 和 `/items/{item_id}` 接收 HTTP 请求。
* 以上两个路径 都接受 `GET` < em > 操作</ em > (也称为 HTTP < em > 方法</ em > )。
* 路径 `/items/{item_id}` 有一个应为 `int` 的< em > 路径参数</ em > `item_id` 。
* 路径 `/items/{item_id}` 有一个可选的 `str` 类型< em > 查询参数</ em > `q` 。
### 交互式 API 文档
### 交互式 API 文档 { #interactive -api-docs }
现在访问 < a href = "http://127.0.0.1:8000/docs" class = "external-link" target = "_blank" > http://127.0.0.1:8000/docs< / a > 。
你会看到自动生成的交互式 API 文档(由 < a href = "https://github.com/swagger-api/swagger-ui" class = "external-link" target = "_blank" > Swagger UI< / a > 生成 ):
你会看到自动生成的交互式 API 文档(由 < a href = "https://github.com/swagger-api/swagger-ui" class = "external-link" target = "_blank" > Swagger UI< / a > 提供 ):

### 可选的 API 文档
### 可选的 API 文档 { #alternative -api-docs }
访问 < a href = "http://127.0.0.1:8000/redoc" class = "external-link" target = "_blank" > http://127.0.0.1:8000/redoc< / a > 。
然后 访问 < a href = "http://127.0.0.1:8000/redoc" class = "external-link" target = "_blank" > http://127.0.0.1:8000/redoc< / a > 。
你会看到另一个自动生成的文档(由 < a href = "https://github.com/Rebilly/ReDoc" class = "external-link" target = "_blank" > ReDoc< / a > 生成 ):
你会看到另一个自动生成的文档(由 < a href = "https://github.com/Rebilly/ReDoc" class = "external-link" target = "_blank" > ReDoc< / a > 提供 ):

## 示例升级
## 示例升级 { #example -upgrade }
现在修改 `main.py` 文件来从 `PUT` 请求中接收 请求体。
现在修改 `main.py` 文件来接收来自 `PUT` 请求的 请求体。
我们借助 Pydantic 来使用标准的 Python 类型声明请求体。
```Python hl_lines="4 9-12 25-27"
from typing import Union
借助 Pydantic,使用标准的 Python 类型来声明请求体。
```Python hl_lines="2 7-10 23-25"
from fastapi import FastAPI
from pydantic import BaseModel
@ -280,7 +294,7 @@ app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: Union[bool, None] = None
is_offer: bool | None = None
@app .get("/")
@ -289,7 +303,7 @@ def read_root():
@app .get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
@ -298,173 +312,248 @@ def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
```
服务器将会自动重载(因为在上面的步骤中你向 `uvicorn` 命令添加了 `--reload` 选项) 。
`fastapi dev` 服务器会自动重载 。
### 交互式 API 文档升级
### 交互式 API 文档升级 { #interactive -api-docs-upgrade }
访问 < a href = "http://127.0.0.1:8000/docs" class = "external-link" target = "_blank" > http://127.0.0.1:8000/docs< / a > 。
现在 访问 < a href = "http://127.0.0.1:8000/docs" class = "external-link" target = "_blank" > http://127.0.0.1:8000/docs< / a > 。
* 交互式 API 文档将会自动更新,并加入 新的请求体:
* 交互式 API 文档会自动更新,并包含 新的请求体:

* 点击「Try it out」按钮,之后你可以填写参数并直接调用 API :
* 点击「Try it out」按钮,它允许你填写参数并直接与 API 交互 :

* 然后点击「Execute」按钮,用户界面将会和 API 进行通信,发送参数, 获取结果并在屏幕上展示:
* 然后点击「Execute」按钮,界面会与你的 API 通信、发送参数、 获取结果并在屏幕上展示:

### 可选文档升级
### 可选文档升级 { #alternative -api-docs-upgrade }
访问 < a href = "http://127.0.0.1:8000/redoc" class = "external-link" target = "_blank" > http://127.0.0.1:8000/redoc< / a > 。
再 访问 < a href = "http://127.0.0.1:8000/redoc" class = "external-link" target = "_blank" > http://127.0.0.1:8000/redoc< / a > 。
* 可选文档同样会体现新加入的请求 参数和请求体:
* 可选文档同样会体现新的查询 参数和请求体:

### 总结
### 总结 { #recap }
总的来说,你就像声明函数的参数类型一样只声明了**一次**请求参数、请求体等的类型 。
总之,你只需要把参数、请求体等的类型作为函数参数**声明一次** 。
你使用了标准的现代 Python 类型来完成声明 。
这些都使用标准的现代 Python 类型即可 。
你不需要去学习新的语法、了解特定库的方法或类,等 等。
你不需要学习新的语法、某个特定库的方法或类 等。
只需要使用 标准的 **Python 及更高版本 ** 。
只需要标准的 **Python** 。
举个例子,比如声明 `int` 类型 :
例如,一个 `int` :
```Python
item_id: int
```
或者一个 更复杂的 `Item` 模型:
或者更复杂的 `Item` 模型:
```Python
item: Item
```
......在进行一次声明之后 ,你将获得:
……通过一次声明 ,你将获得:
* 编辑器支持,包括:
* 自动补全
* 类型检查
* 自动补全。
* 类型检查。
* 数据校验:
* 在校验失败时自动生成清晰的错误信息
* 对多层嵌套的 JSON 对象依然执行校验
* < abbr title = "也被称为:序列化或解析 " > 转换< / abbr > 来自网络请求的输入数据为 Python 数据类型。包括以下数据 :
* JSON
* 路径参数
* 查询参数
* Cookies
* 请求头
* 表单
* 文件
* < abbr title = "也被称为:序列化或解析 " > 转换< / abbr > 输出的数据:转换 Python 数据类型为供网络传输的 JSON 数据 :
* 转换 Python 基础 类型 (`str`、 `int` 、 `float` 、 `bool` 、 `list` 等)
* `datetime` 对象
* `UUID` 对象
* 数据库模型
* ......以及更多其他类型
* 当数据无效时自动生成清晰的错误信息。
* 即便是多层嵌套的 JSON 对象也会进行校验。
* 输入数据的 < abbr title = "也被称为:序列化、解析、编组 " > 转换< / abbr > :从网络读取到 Python 数据和类型。读取来源 :
* JSON。
* 路径参数。
* 查询参数。
* Cookies。
* Headers。
* Forms。
* Files。
* 输出数据的 < abbr title = "也被称为:序列化、解析、编组 " > 转换< / abbr > :从 Python 数据和类型转换为网络数据(JSON) :
* 转换 Python 类型(`str`、`int`、`float`、`bool`、`list` 等)。
* `datetime` 对象。
* `UUID` 对象。
* 数据库模型。
* ……以及更多。
* 自动生成的交互式 API 文档,包括两种可选的用户界面:
* Swagger UI
* ReDoc
* Swagger UI。
* ReDoc。
---
回到前面 的代码示例,**FastAPI** 将会:
回到之 前的代码示例,**FastAPI** 将会:
* 校验 `GET` 和 `PUT` 请求的路径中是否含有 `item_id` 。
* 校验 `GET` 和 `PUT` 请求的路径中是否包 含 `item_id` 。
* 校验 `GET` 和 `PUT` 请求中的 `item_id` 是否为 `int` 类型。
* 如果不是,客户端将会收 到清晰有用的错误信息。
* 检查 `GET` 请求中是否有命 名为 `q` 的可选查询参数(比 如 `http://127.0.0.1:8000/items/foo?q=somequery` )。
* 因为 `q` 被声明为 `= None` ,所以它是可选的。
* 如果没有 `None` 它将会是必需的 (如 `PUT` 例子中的请求体) 。
* 对于访问 `/items/{item_id}` 的 `PUT` 请求,将请求体读取为 JSON 并 :
* 检查是否有必需属性 `name` 并且值为 `str` 类型 。
* 检查是否有必需属性 `price` 并且值为 `float` 类型 。
* 检查是否有可选属性 `is_offer` , 如果有的话值应该为 `bool` 类型 。
* 以上过程对于多层嵌套的 JSON 对象同样也会执行
* 自动对 JSON 进行转换或转换成 JSON 。
* 通过 OpenAPI 文档来记录所有内容,可被 用于:
* 交互式文档系统
* 许 多编程 语言的客户端代码自动生成系统
* 直接提供 2 种交互式文档 w eb 界面。
* 如果不是,客户端会看 到清晰有用的错误信息。
* 对于 `GET` 请求,检查是否存在 名为 `q` 的可选查询参数(如 `http://127.0.0.1:8000/items/foo?q=somequery` )。
* 因为参数 `q` 被声明为 `= None` ,所以它是可选的。
* 如果没有 `None` ,它就是必需的(就像 `PUT` 情况下的请求体) 。
* 对于发送到 `/items/{item_id}` 的 `PUT` 请求,把请求体作为 JSON 读取 :
* 检查是否存在必需属性 `name` ,且为 `str` 。
* 检查是否存在必需属性 `price` ,且为 `float` 。
* 检查是否存在可选属性 `is_offer` ,如果存在则应为 `bool` 。
* 对于多层嵌套的 JSON 对象,同样适用。
* 自动完成 JSON 的读取与输出转换 。
* 使用 OpenAPI 记录所有内容,可 用于:
* 交互式文档系统。
* 多语言的客户端代码自动生成系统。
* 直接提供 2 种交互式文档 W eb 界面。
---
虽然我们才刚刚开始,但其实你已经了解了这一切是如何工作的 。
我们只是浅尝辄止,但你已经大致了解其工作方式了 。
尝试更改下面这行代码 :
尝试把这一行 :
```Python
return {"item_name": item.name, "item_id": item_id}
```
...... 从:
…… 从:
```Python
... "item_name": item.name ...
```
...... 改为:
…… 改为:
```Python
... "item_price": item.price ...
```
......注意观察编辑器是如何自动补全属性并且还 知道它们的类型:
……看看你的编辑器如何自动补全属性并 知道它们的类型:

< a href = "https://fastapi.tiangolo.com/zh/tutorial/" > 教程 - 用户指南< / a > 中有包含更多特性的更完整示例 。
更多包含更多特性的完整示例,请参阅 < a href = "https://fastapi.tiangolo.com/zh/tutorial/" > 教程 - 用户指南< / a > 。
**剧透警告**: 教程 - 用户指南中的内容有 :
**剧透警告**:教程 - 用户指南包括 :
* 对来自不同地方的参数进行声明,如:**请求头**、**cookies**、**form 表单**以及**上传的文件**。
* 如何设置**校验约束**如 `maximum_length` 或者 `regex` 。
* 一个强大并易于使用的 ** < abbr title = "也被称为 components, resources, providers, services, injectables" > 依赖注入</ abbr > ** 系统。
* 安全性和身份验证,包括通过 **JWT 令牌**和 **HTTP 基本身份认证**来支持 **OAuth2** 。
* 更进阶(但同样简单)的技巧来声明 **多层嵌套 JSON 模型** (借助 Pydantic)。
* 许多额外功能(归功于 Starlette)比如:
* 来自不同位置的**参数**声明:**headers**、**cookies**、**form 字段**和**文件**。
* 如何设置**校验约束**,如 `maximum_length` 或 `regex` 。
* 功能强大且易用的 ** < abbr title = "也被称为 components、resources、providers、services、injectables" > 依赖注入</ abbr > ** 系统。
* 安全与认证,包括对 **OAuth2** 、**JWT tokens** 和 **HTTP Basic** 认证的支持。
* 更高级(但同样简单)的 **多层嵌套 JSON 模型** 声明技巧(得益于 Pydantic)。
* 通过 < a href = "https://strawberry.rocks" class = "external-link" target = "_blank" > Strawberry</ a > 等库进行 **GraphQL** 集成。
* 许多额外特性(归功于 Starlette),例如:
* * *WebSockets**
* * *GraphQL**
* 基于 HTTPX 和 `pytest` 的极其简单的测试
* * *CORS**
* * *Cookie Sessions**
* ......以及更多
* ……以及更多。
### 部署你的应用(可选) { #deploy -your-app-optional }
你可以选择把 FastAPI 应用部署到 < a href = "https://fastapicloud.com" class = "external-link" target = "_blank" > FastAPI Cloud< / a > ,如果还没有的话去加入候补名单吧。🚀
如果你已经有 **FastAPI Cloud** 账号(我们从候补名单邀请了你 😉),你可以用一个命令部署你的应用。
部署前,先确认已登录:
< div class = "termy" >
```console
$ fastapi login
You are logged in to FastAPI Cloud 🚀
```
## 性能
< / div >
然后部署你的应用:
< div class = "termy" >
```console
$ fastapi deploy
Deploying to FastAPI Cloud...
✅ Deployment successful!
🐔 Ready the chicken! Your app is ready at https://myapp.fastapicloud.dev
```
< / div >
就这样!现在你可以通过该 URL 访问你的应用了。✨
#### 关于 FastAPI Cloud { #about -fastapi-cloud }
**< a href = "https://fastapicloud.com" class = "external-link" target = "_blank" > FastAPI Cloud</ a > ** 由 **FastAPI** 的同一位作者和团队打造。
它让你以最小的工作量就能**构建**、**部署**并**访问**一个 API。
它把用 FastAPI 构建应用时的**开发者体验**带到了部署到云上的过程。🎉
独立机构 TechEmpower 所作的基准测试结果显示,基于 Uvicorn 运行的 **FastAPI** 程序是 < a href = "https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class = "external-link" target = "_blank" > 最快的 Python web 框架之一</ a > ,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用了它们)。(*)
FastAPI Cloud 是「FastAPI and friends」开源项目的主要赞助方和资金提供者。✨
想了解更多,请查阅 < a href = "https://fastapi.tiangolo.com/zh/benchmarks/" class = "internal-link" target = "_blank" > 基准测试< / a > 章节。
#### 部署到其他云厂商 { #deploy -to-other-cloud-providers }
## 可选依赖
FastAPI 是开源且基于标准的。你可以部署 FastAPI 应用到你选择的任意云厂商。
用于 Pydantic:
按照你的云厂商的指南部署 FastAPI 应用即可。🤓
## 性能 { #performance }
独立机构 TechEmpower 的基准测试显示,运行在 Uvicorn 下的 **FastAPI** 应用是< a href = "https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7" class = "external-link" target = "_blank" > 最快的 Python 框架之一</ a > ,仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用它们)。(*)
想了解更多,请参阅< a href = "https://fastapi.tiangolo.com/zh/benchmarks/" class = "internal-link" target = "_blank" > 基准测试< / a > 章节。
## 依赖项 { #dependencies }
FastAPI 依赖 Pydantic 和 Starlette。
### `standard` 依赖 { #standard -dependencies }
当你通过 `pip install "fastapi[standard]"` 安装 FastAPI 时,会包含 `standard` 组的一些可选依赖:
Pydantic 使用:
* < a href = "https://github.com/JoshData/python-email-validator" target = "_blank" > < code > email-validator< / code > < / a > - 用于 email 校验。
用于 Starlette:
Starlette 使用:
* < a href = "https://www.python-httpx.org" target = "_blank" >< code > httpx</ code ></ a > - 使用 `TestClient` 时需要。
* < a href = "https://jinja.palletsprojects.com" target = "_blank" > < code > jinja2< / code > < / a > - 使用默认模板配置时需要。
* < a href = "https://github.com/Kludex/python-multipart" target = "_blank" >< code > python-multipart</ code ></ a > - 使用 `request.form()` 支持表单< abbr title = "将 HTTP 请求中的字符串转换为 Python 数据" > 「解析」</ abbr > 时需要。
FastAPI 使用:
* < a href = "https://www.uvicorn.dev" target = "_blank" >< code > uvicorn</ code ></ a > - 加载并提供你的应用的服务器。包含 `uvicorn[standard]` ,其中包含高性能服务所需的一些依赖(例如 `uvloop` )。
* `fastapi-cli[standard]` - 提供 `fastapi` 命令。
* 其中包含 `fastapi-cloud-cli` ,它允许你将 FastAPI 应用部署到 < a href = "https://fastapicloud.com" class = "external-link" target = "_blank" > FastAPI Cloud</ a > 。
### 不包含 `standard` 依赖 { #without -standard-dependencies }
如果你不想包含这些 `standard` 可选依赖,可以使用 `pip install fastapi` ,而不是 `pip install "fastapi[standard]"` 。
### 不包含 `fastapi-cloud-cli` { #without -fastapi-cloud-cli }
如果你想安装带有 standard 依赖但不包含 `fastapi-cloud-cli` 的 FastAPI,可以使用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"` 。
### 其他可选依赖 { #additional -optional-dependencies }
还有一些你可能想安装的可选依赖。
* < a href = "https://www.python-httpx.org" target = "_blank" >< code > httpx</ code ></ a > - 使用 `TestClient` 时安装。
* < a href = "https://jinja.palletsprojects.com" target = "_blank" > < code > jinja2< / code > < / a > - 使用默认模板配置时安装。
* < a href = "https://github.com/Kludex/python-multipart" target = "_blank" >< code > python-multipart</ code ></ a > - 需要通过 `request.form()` 对表单进行< abbr title = "将来自 HTTP 请求中的字符串转换为 Python 数据类型" > 「解析」</ abbr > 时安装。
* < a href = "https://pythonhosted.org/itsdangerous/" target = "_blank" >< code > itsdangerous</ code ></ a > - 需要 `SessionMiddleware` 支持时安装。
* < a href = "https://pyyaml.org/wiki/PyYAMLDocumentation" target = "_blank" >< code > pyyaml</ code ></ a > - 使用 Starlette 提供的 `SchemaGenerator` 时安装(有 FastAPI 你可能并不需要它)。
* < a href = "https://graphene-python.org/" target = "_blank" >< code > graphene</ code ></ a > - 需要 `GraphQLApp` 支持时安装。
额外的 Pydantic 可选依赖:
用于 FastAPI / Starlette:
* < a href = "https://docs.pydantic.dev/latest/usage/pydantic_settings/" target = "_blank" > < code > pydantic-settings< / code > < / a > - 用于配置管理。
* < a href = "https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/" target = "_blank" > < code > pydantic-extra-types< / code > < / a > - 用于在 Pydantic 中使用的额外类型。
* < a href = "https://www.uvicorn.dev" target = "_blank" > < code > uvicorn< / code > < / a > - 用于加载和运行你的应用程序的服务器。
* < a href = "https://github.com/ijl/orjson" target = "_blank" >< code > orjson</ code ></ a > - 使用 `ORJSONResponse` 时安装。
* < a href = "https://github.com/esnme/ultrajson" target = "_blank" >< code > ujson</ code ></ a > - 使用 `UJSONResponse` 时安装。
额外的 FastAPI 可选依赖:
你可以通过 `pip install "fastapi[all]"` 命令来安装以上所有依赖。
* < a href = "https://github.com/ijl/orjson" target = "_blank" >< code > orjson</ code ></ a > - 使用 `ORJSONResponse` 时需要。
* < a href = "https://github.com/esnme/ultrajson" target = "_blank" >< code > ujson</ code ></ a > - 使用 `UJSONResponse` 时需要。
## 许可协议
## 许可协议 { #license }
该项目遵循 MIT 许可协议。