@ -13,7 +13,7 @@ include_yaml:
< a href = "https://fastapi.tiangolo.com/zh" > < img src = "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt = "FastAPI" > < / a >
< / p >
< p align = "center" >
< em > FastAPI 框架,高性能,易于学习,高效编码,生产可用 < / em >
< em > FastAPI 框架,高性能。容易上手。开发更快。开箱即用,能上生产。 < / em >
< / p >
< p align = "center" >
< a href = "https://github.com/fastapi/fastapi/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" >
@ -32,26 +32,26 @@ include_yaml:
---
**文档**: [https://fastapi.tiangolo.com/zh ](https://fastapi.tiangolo.com/zh )
文档: [https://fastapi.tiangolo.com/zh ](https://fastapi.tiangolo.com/zh )
**源码**: [https://github.com/fastapi/fastapi ](https://github.com/fastapi/fastapi )
源码: [https://github.com/fastapi/fastapi ](https://github.com/fastapi/fastapi )
---
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框架,使用 Python 并基于标准的 Python 类型提示 。
FastAPI 是一个现代、快速(高性能)的 Web 框架。用标准的 Python 类型标注来构建 API 。
关键 特性:
核心 特性:
* **快速** :极高性能,可与 **NodeJS** 和 **Go** 并肩(归功于 Starlette 和 Pydantic)。[最快的 Python 框架之一](#performance)。
* **高效编码** :功能开发速度提升约 200% ~ 300%。*
* ** 更少 bug** :人为(开发者)错误减少约 40% 。*
* ** 直观** :极佳的 编辑器支持。处处皆可 < dfn title = "也被 称为:自动完成、自动 补全、IntelliSense" > 自动 补全</ dfn > 。更少的 调试时间。
* **易用** :为易用和易学而设计。更少的文档阅读 时间。
* **简短** :最小化代码重复。一次参数声明即可获得多种功能。更少的 bug。
* **健壮** :生产可用级代码。并带有自动生成的 交互式文档。
* **标准化** :基于(并完全兼容)API 的开放标准:[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前称为 Swagger)和 [JSON Schema ](https://json-schema.org/ )。
* 快:性能很高。和 **NodeJS** 、**Go** 一个量级(得益于 Starlette 和 Pydantic)。[Python 里最快的 框架之一](#performance)。
* 开发快:开发效率提升大约 200% 到 300%。*
* 更少的 bug:减少大约 40% 的 人为(开发者)错误。*
* 直观:编辑器支持好 。< dfn title = "也称为:自动补全、autocompletion、 IntelliSense" > 补全< / dfn > 无处不在 。更少调试时间。
* 简单:易用、易学。更少查文档 时间。
* 精简:最小化重复代码。一次声明,多处生效。更少 bug。
* 稳健:代码上生产。自带 交互式文档。
* 基于标准:完全兼容 API 开放标准:[OpenAPI](https://github.com/OAI/OpenAPI-Specification)(以前叫 Swagger)和 [JSON Schema ](https://json-schema.org/ )。
< small > * 基于某内部开发团队在构建生产应用时 的测试估算。< / small >
< small > * 基于内部团队在真实生产项目中 的测试估算。< / small >
## 赞助商 { #sponsors }
@ -65,7 +65,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
{% endfor -%}
< / div >
### 金牌 赞助商 { #gold -sponsors }
### 黄 金赞助商 { #gold -sponsors }
< div class = "fastapi-sponsors fastapi-sponsors--gold" >
{% for sponsor in sponsors.gold -%}
@ -73,7 +73,7 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
{% endfor -%}
< / div >
### 银牌 赞助商 { #silver -sponsors }
### 白 银赞助商 { #silver -sponsors }
< div class = "fastapi-sponsors fastapi-sponsors--silver" >
{% for sponsor in sponsors.silver -%}
@ -105,19 +105,19 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
< / div >
< div class = "fastapi-opinions__panel" id = "fo-panel-microsoft" role = "tabpanel" aria-labelledby = "fo-tab-microsoft" tabindex = "0" >
< blockquote class = "fastapi-opinions__quote" > “我最近大量使 用 < strong > FastAPI< / strong > 。我实际上计划把它用于我 团队在 < strong > 微软的机器学习(ML) 服务< / strong > 。其中一些正在集成进核心 < strong > Windows< / strong > 产品以及 一些 < strong > Office< / strong > 产品。”< / blockquote >
< blockquote class = "fastapi-opinions__quote" > “我这段时间 用 < strong > FastAPI< / strong > 用得很多。打算把我们 团队在 < strong > Microsoft 的 ML 服务< / strong > 全都切到它上面。一些已经集成进核心的 < strong > Windows< / strong > 产品,还有 一些 < strong > Office< / strong > 产品。”< / blockquote >
< div class = "fastapi-opinions__attr" > — Kabir Khan,< strong > Microsoft< / strong > < a href = "https://github.com/fastapi/fastapi/pull/26" > (ref)< / a > < / div >
< / div >
< div class = "fastapi-opinions__panel" id = "fo-panel-uber" role = "tabpanel" aria-labelledby = "fo-tab-uber" tabindex = "0" hidden >
< blockquote class = "fastapi-opinions__quote" > “我们采用了 < strong > FastAPI< / strong > 库来启动一个可查询获取< strong > 预测结果< / strong > 的 < strong > REST< / strong > 服务器。” < em > [用于 Ludwig]< / em > < / blockquote >
< div class = "fastapi-opinions__attr" > — Piero Molino,Yaroslav Dudin, Sai Sumanth Miryala,< strong > Uber< / strong > < a href = "https://eng.uber.com/ludwig-v0-2/" > (ref)< / a > < / div >
< blockquote class = "fastapi-opinions__quote" > “我们采用了 < strong > FastAPI< / strong > 库来启动一个 < strong > REST< / strong > 服务器,通过它查询得到< strong > 预测< / strong > 。” < em > [用于 Ludwig]< / em > < / blockquote >
< div class = "fastapi-opinions__attr" > — Piero Molino, Yaroslav Dudin, Sai Sumanth Miryala,< strong > Uber< / strong > < a href = "https://eng.uber.com/ludwig-v0-2/" > (ref)< / a > < / div >
< / div >
< div class = "fastapi-opinions__panel" id = "fo-panel-netflix" role = "tabpanel" aria-labelledby = "fo-tab-netflix" tabindex = "0" hidden >
< blockquote class = "fastapi-opinions__quote" > “< strong > Netflix< / strong > 很高兴宣布 开源我们的< strong > 危机管理< / strong > 编排框架:< strong > Dispatch< / strong > !” < em > [使用 FastAPI 构建]< / em > < / blockquote >
< div class = "fastapi-opinions__attr" > — Kevin Glisson,Marc Vilanova, Forest Monsen,< strong > Netflix< / strong > < a href = "https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" > (ref)< / a > < / div >
< blockquote class = "fastapi-opinions__quote" > “< strong > Netflix< / strong > 很高兴开源我们的< strong > 危机管理< / strong > 编排框架:< strong > Dispatch< / strong > !” < em > [基于 FastAPI 构建]< / em > < / blockquote >
< div class = "fastapi-opinions__attr" > — Kevin Glisson, Marc Vilanova, Forest Monsen,< strong > Netflix< / strong > < a href = "https://netflixtechblog.com/introducing-dispatch-da4b8a2a8072" > (ref)< / a > < / div >
< / div >
< div class = "fastapi-opinions__panel" id = "fo-panel-cisco" role = "tabpanel" aria-labelledby = "fo-tab-cisco" tabindex = "0" hidden >
< blockquote class = "fastapi-opinions__quote" > “如果有人正在构建生产级的 Python API ,我强烈推荐 < strong > FastAPI< / strong > 。它< strong > 设计优雅< / strong > 、< strong > 使用 简单< / strong > 且 < strong > 高度 可扩展< / strong > —— 它已经成为我们 API 优先开发战略中 的< strong > 关键组件< / strong > 。”< / blockquote >
< blockquote class = "fastapi-opinions__quote" > “如果你在找生产可用的 Python API 框架 ,我强烈推荐 < strong > FastAPI< / strong > 。它< strong > 设计优雅< / strong > 、< strong > 简单易用 < / strong > 、 < strong > 可扩展性强 < / strong > ——已经成了我们 API-first 开发战略 的< strong > 关键组件< / strong > 。”< / blockquote >
< div class = "fastapi-opinions__attr" > — Deon Pillsbury,< strong > Cisco< / strong > < a href = "https://www.linkedin.com/posts/deonpillsbury_cisco-cx-python-activity-6963242628536487936-trAp/" > (ref)< / a > < / div >
< / div >
< / div >
@ -125,25 +125,25 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
< div class = "only-github" markdown = "1" >
「_[...] 我最近大量使用 **FastAPI** 。[...] 我实际上计划把它用于我团队在 **微软的机器学习(ML)服务** 。其中一些正在集成进核心 **Windows** 产品以及一些 **Office** 产品。_」
“_[...] 我这段时间用 **FastAPI** 用得很多。[...] 打算把我们团队在 **Microsoft 的 ML 服务**全都切到它上面。一些已经集成进核心的 **Windows** 产品,还有一些 **Office** 产品。_”
< div style = "text-align: right; margin-right: 10%;" > Kabir Khan - < strong > Microsoft< / strong > < a href = "https://github.com/fastapi/fastapi/pull/26" > < 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/" > < small > (ref)< / small > < / a > < / div >
< div style = "text-align: right; margin-right: 10%;" > Piero Molino, Yaroslav Dudin, and Sai Sumanth Miryala - < strong > Uber< / strong > < a href = "https://eng.uber.com/ludwig-v0-2/" > < 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" > < small > (ref)< / small > < / a > < / div >
< 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" > < small > (ref)< / small > < / a > < / div >
---
「_如果有人正在构建生产级的 Python API,我强烈推荐 **FastAPI** 。它**设计优雅**、**使用简单**且**高度可扩展**,它已经成为我们 API 优先开发战略中的**关键组件**,并驱动了许多自动化和服务,比如我们的 Virtual TAC Engineer。_」
“_如果你在找生产可用的 Python API 框架,我强烈推荐 **FastAPI** 。它**设计优雅**、**简单易用**、**可扩展性强**,已经成了我们 API-first 开发战略的**关键组件**,驱动了很多自动化和服务,比如我们的 Virtual TAC Engineer。_”
< 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/" > < small > (ref)< / small > < / a > < / div >
@ -153,34 +153,34 @@ FastAPI 是一个用于构建 API 的现代、快速(高性能)的 Web 框
## FastAPI 大会 { #fastapi -conf }
[**FastAPI Conf '26** ](https://fastapiconf.com ) 将于 **2026 年 10 月 28 日** 在 **荷兰阿姆斯特丹** 举行。来自源头的 FastAPI 干货 。🎤
[**FastAPI Conf '26** ](https://fastapiconf.com ) 将在 **2026 年 10 月 28 日** 于 **荷兰阿姆斯特丹** 举办。全是 FastAPI 干货,来自源头 。🎤
< a class = "fastapi-feature-banner" href = "https://fastapiconf.com" > < img src = "https://fastapi.tiangolo.com/img/fastapi-conf.jpeg" alt = "FastAPI Conf '26 - 2026 年 10 月 28 日 - 荷兰阿姆斯特丹 " > < / a >
< a class = "fastapi-feature-banner" href = "https://fastapiconf.com" > < img src = "https://fastapi.tiangolo.com/img/fastapi-conf.jpeg" alt = "FastAPI Conf '26 - October 28, 2026 - Amsterdam, NL " > < / a >
## FastAPI 迷你 纪录片 { #fastapi -mini-documentary }
## FastAPI 微 纪录片 { #fastapi -mini-documentary }
在 2025 年末发布了一部 [FastAPI 迷你纪录片 ](https://www.youtube.com/watch?v=mpR8ngthqiE ),你可以在线观 看:
这里有一部 [FastAPI 微纪录片 ](https://www.youtube.com/watch?v=mpR8ngthqiE ),在 2025 年底发布。可以在线 看:
< a class = "fastapi-feature-banner" href = "https://www.youtube.com/watch?v=mpR8ngthqiE" > < img src = "https://fastapi.tiangolo.com/img/fastapi-documentary.jpg" alt = "FastAPI 迷你纪录片 " > < / a >
< a class = "fastapi-feature-banner" href = "https://www.youtube.com/watch?v=mpR8ngthqiE" > < img src = "https://fastapi.tiangolo.com/img/fastapi-documentary.jpg" alt = "FastAPI Mini Documentary " > < / a >
## **Typer** ,命令行中 的 FastAPI { #typer -the-fastapi-of-clis }
## Typer:CLI 里 的 FastAPI { #typer -the-fastapi-of-clis }
< a href = "https://typer.tiangolo.com" > < img src = "https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg" style = "width: 20%;" > < / a >
如果你要开发一个用于终端而不是 Web API 的 < abbr title = "Command Line Interface - 命令行界面" > CLI</ abbr > 应用,看看 [**Typer** ](https://typer.tiangolo.com/ )。
如果你要做一个终端里用 的 < abbr title = "Command Line Interface - 命令行界面" > CLI</ abbr > 应用,不是 Web API ,看看 [**Typer** ](https://typer.tiangolo.com/ )。
**Typer** 是 FastAPI 的小同胞。它的目标是成为**命令行中的 FastAPI** 。⌨️ 🚀
**Typer** 是 FastAPI 的小老弟。目标是做 **CLI 里的 FastAPI** 。⌨️ 🚀
## 依赖 { #requirements }
## 依赖和基座 { #requirements }
FastAPI 站在巨人的 肩膀之 上:
FastAPI 站在巨人肩膀上:
* [Starlette ](https://www.starlette.dev/ ) 负责 Web 部分。
* [Pydantic ](https://docs.pydantic.dev/ ) 负责数据部分。
## 安装 { #installation }
创建并激活一个 [虚拟环境 ](https://fastapi.tiangolo.com/zh/virtual-environments/ ),然后安装 FastAPI:
先 创建并激活一个[虚拟环境](https://fastapi.tiangolo.com/zh/virtual-environments/),然后安装 FastAPI:
< div class = "termy" >
@ -192,13 +192,13 @@ $ pip install "fastapi[standard]"
< / div >
**Note**: 请确保把 `"fastapi[standard]"` 用引号包起来,以保证在所有终端中都能正常工作 。
注意:把 "fastapi[standard]" 加上引号。所有终端都能正常识别 。
## 示例 { #example }
### 创建 { #create -it }
创建文件 `main.py` ,内容如下 :
新建文件 `main.py` ,写入 :
```Python
from fastapi import FastAPI
@ -217,9 +217,9 @@ def read_item(item_id: int, q: str | None = None):
```
< details markdown = "1" >
< summary > 或者使 用 < code > async def< / code > ...< / summary >
< summary > 或者用 < code > async def< / code > ...< / summary >
如果你的代码里会 用到 `async` / `await` ,请使 用 `async def` :
如果你的代码用到了 `async` / `await` ,就 用 `async def` :
```Python hl_lines="7 12"
from fastapi import FastAPI
@ -237,15 +237,15 @@ async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
```
**Note**:
注意:
如果你不确定,请查看文档中 _"In a hurry?"_ 章节 的 [`async` 和 `await` ](https://fastapi.tiangolo.com/zh/async/#in-a-hurry ) 部分 。
不确定的话,去看「In a hurry?」里关于文档中 的 [`async` 和 `await` ](https://fastapi.tiangolo.com/zh/async/#in-a-hurry )。
< / details >
### 运行 { #run -it }
用下面的命令运行服务器 :
启动服务 :
< div class = "termy" >
@ -275,54 +275,54 @@ INFO: Application startup complete.
< / div >
< details markdown = "1" >
< summary > 关于命令 < code > fastapi dev< / code > ...< / summary >
< summary > 关于 < code > fastapi dev< / code > 命令 ...< / summary >
`fastapi dev` 命令会读取你的 `main.py` 文件,检测其中的 **FastAPI** 应用,并使 用 [Uvicorn ](https://www.uvicorn.dev ) 启动服务器。
`fastapi dev` 会自动读取你的 `main.py` ,检测里面的 **FastAPI** 应用,然后 用 [Uvicorn ](https://www.uvicorn.dev ) 启动服务器。
默认情况下,`fastapi dev` 会在本地 开发时 启用 自动重载。
默认开启自动重载,方便本地开发 。
你可以在 [FastAPI CLI 文档 ](https://fastapi.tiangolo.com/zh/fastapi-cli/ ) 中了解更多 。
更多见 [FastAPI CLI 文档 ](https://fastapi.tiangolo.com/zh/fastapi-cli/ )。
< / details >
### 检 查 { #check -it }
### 查看 { #check -it }
用浏览器打开 [http://127.0.0.1:8000/items/5?q=somequery ](http://127.0.0.1:8000/items/5?q=somequery )。
打开浏览器访问 [http://127.0.0.1:8000/items/5?q=somequery ](http://127.0.0.1:8000/items/5?q=somequery )。
你会看到如下 JSON 响应:
你会看到 JSON 响应:
```JSON
{"item_id": 5, "q": "somequery"}
```
你已经创建了一个 API,它可以 :
你已经写好了一个 API,它 :
* 在路径 `/` 和 `/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` 。
* 接收 `/` 和 `/items/{item_id}` 两个路径的 HTTP 请求。
* 这两个路径都接收 `GET` 操作(也叫 HTTP 方法 )。
* `/items/{item_id}` 的路径参数 `item_id` 必须是 `int ` 。
* `/items/{item_id}` 还 有一个可选的 `str` 类型查询参数 `q` 。
### 交互式 API 文档 { #interactive -api-docs }
现在 访问 [http://127.0.0.1:8000/docs ](http://127.0.0.1:8000/docs )。
访问 [http://127.0.0.1:8000/docs ](http://127.0.0.1:8000/docs )。
你会看到自动生成的交互式 API 文档(由 [Swagger UI ](https://github.com/swagger-api/swagger-ui ) 提供):

### 可选的 API 文档 { #alternative -api-docs }
### 另一套 API 文档 { #alternative -api-docs }
然后 访问 [http://127.0.0.1:8000/redoc ](http://127.0.0.1:8000/redoc )。
再 访问 [http://127.0.0.1:8000/redoc ](http://127.0.0.1:8000/redoc )。
你会看到另一个自动生成的 文档(由 [ReDoc ](https://github.com/Rebilly/ReDoc ) 提供):
你会看到另一套自动 文档(由 [ReDoc ](https://github.com/Rebilly/ReDoc ) 提供):

## 示例升级 { #example -upgrade }
## 升级 示例 { #example -upgrade }
现在修改 `main.py` 文件来接收来自 `PUT` 请求的请求体 。
现在改一下 `main.py` ,让它能接收 `PUT` 请求的 body 。
借助 Pydantic,使用标准的 Python 类型来声明请求体。
用标准 Python 类型声明 body,多亏了 Pydantic:
```Python hl_lines="2 7-10 23-25"
from fastapi import FastAPI
@ -352,43 +352,43 @@ def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
```
`fastapi dev` 服务器 会自动重载。
`fastapi dev` 会自动重载。
### 交互式 API 文档升级 { #interactive -api-docs-upgrade }
### 交互式文档同步 升级 { #interactive -api-docs-upgrade }
现在 访问 [http://127.0.0.1:8000/docs ](http://127.0.0.1:8000/docs )。
访问 [http://127.0.0.1:8000/docs ](http://127.0.0.1:8000/docs )。
* 交互式 API 文档会自动更新,并包含新的请求体 :
* 交互式文档会自动更新。包含新的 body :

* 点击「Try it out」按钮,它允许你填写参数并直接与 API 交互:
* 点 “Try it out” 按钮。可以填参数,直接和 API 交互:

* 然后点击「Execute」按钮,界面会与你的 API 通信、发送参数、获取结果并在屏幕上 展示:
* 然后点 “Execute”。界面会调用你的 API,发送参数,拿到结果并 展示:

### 可选文档 升级 { #alternative -api-docs-upgrade }
### 另一套文档同步 升级 { #alternative -api-docs-upgrade }
再访问 [http://127.0.0.1:8000/redoc ](http://127.0.0.1:8000/redoc )。
* 可选文档同样会体现新的查询参数和请求体 :
* 这套文档也会反映新的查询参数和 body :

### 总 结 { #recap }
### 小 结 { #recap }
总之,你只需要把参数、请求体等的类型作为函数参数**声明一次** 。
总结一下。你只需要在函数参数里声明一次参数类型、body 等 。
这些都使 用标准 的现代 Python 类型即可 。
用的就是 现代标准 Python 类型。
你不需要学习新的语法、某个特定库的方法或类等 。
不用学一堆新语法、不用背某个库的方法或类 。
只需要 标准的 **Python** 。
就是 标准的 **Python** 。
例 如,一个 `int` :
比 如,一个 `int` :
```Python
item_id: int
@ -400,101 +400,101 @@ item_id: int
item: Item
```
……通过一次声明,你将获得 :
...只要这一个声明,你就能得到 :
* 编辑器支持,包括:
* 自动 补全。
* 补全。
* 类型检查。
* 数据校验:
* 当数据无效时自动生成清晰的错误信息 。
* 即便是多层嵌套的 JSON 对象也会进行 校验。
* < dfn title = "也被称为:序列化、解析、编组 " > 转换< / dfn > 输入数据 :从网络读取 到 Python 数据和类型。读取来源:
* 数据不合法时自动抛出清晰的错误 。
* 支持深层嵌套 JSON 的 校验。
* 输入数据的 < dfn title = "也称为:序列化、解析、封送 " > 转换< / dfn > :从网络到 Python 数据和类型。读取来源:
* JSON。
* 路径参数。
* 查询参数。
* Cookies。
* Headers。
* Forms 。
* Files 。
* < dfn title = "也被称为:序列化、解析、编组 " > 转换< / dfn > 输出数据:从 Python 数据和类型转换为 网络数据(JSON):
* 转换 Python 类型(`str`、`int`、`float`、`bool`、`list` 等)。
* 表单 。
* 文件 。
* 输出数据的 < dfn title = "也称为:序列化、解析、封送 " > 转换< / dfn > :从 Python 数据和类型到 网络数据(JSON):
* 转换 Python 基本 类型(`str`、`int`、`float`、`bool`、`list` 等)。
* `datetime` 对象。
* `UUID` 对象。
* 数据库模型。
* ……以及更多 。
* 自动生成的交互式 API 文档,包括两种可选的用户界面 :
* ...等等 。
* 自动生成的交互式 API 文档,有两套 UI :
* Swagger UI。
* ReDoc。
---
回到之前的代码示例,**FastAPI** 将 会:
* 校验 `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 的读取与输出 转换。
* 使用 OpenAPI 记录所有内容,可用于 :
回到上面的代码示例,**FastAPI** 会:
* 校验 `GET` 和 `PUT` 请求的路径里有 `item_id` 。
* 校验 `GET` 和 `PUT` 请求里的 `item_id` 是 `int` 。
* 如果不是,客户端会看到清晰有用的错误。
* 对 `GET` 到 `/items/{item_id}` 的请求,检查是否有 名为 `q` 的可选查询参数(比 如 `http://127.0.0.1:8000/items/foo?q=somequery` )。
* `q` 参数声明了 `= None` ,所以它是可选的。
* 去掉 `None` 就会变成必填(`PUT` 里的 body 也是必填 )。
* 对 `/items/{item_id}` 的 `PUT` 请求,把 body 当作 JSON 读取:
* 检查是否有必填属性 `name` ,类型 为 `str` 。
* 检查是否有必填属性 `price` ,类型 为 `float` 。
* 检查是否有可选属性 `is_offer` ,如果有则必须是 `bool` 。
* 这些校验也适用于深层嵌套的 JSON 。
* 自动在 JSON 和 Python 之间 转换。
* 用 OpenAPI 文档化一切,可以被以下工具使用 :
* 交互式文档系统。
* 多语言的客户端代码自动 生成系统。
* 直接提供 2 种 交互式文档 Web 界面。
* 多语言的自动 客户端代码生成系统。
* 直接提供两套 交互式文档 Web 界面。
---
我们只是浅尝辄止,但你已经大致了解其工作方式 了。
这里只是开了个头,但你已经知道它怎么运作 了。
尝试 把这一行:
把这一行:
```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 > 。
**剧透警告**:教程 - 用户指南包括 :
剧透:教程 - 用户指南包含 :
* 来自不同位置的**参数**声明:**headers**、**cookies**、**form 字段**和 **文件**。
* 如何设置**校验约束**,如 `maximum_length` 或 `regex` 。
* 功能强大且易用的 ** < dfn title = "也被 称为:组件、资源、提供者、服务、可注入项 " > 依赖注入</ dfn > ** 系统。
* 安全与认证,包括对 **OAuth2** 、**JWT tokens** 和 **HTTP Basic** 认证的支持 。
* 更高级(但同样简单)的 **多层嵌套 JSON 模型** 声明技巧(得益于 Pydantic)。
* 通过 [Strawberry ](https://strawberry.rocks ) 等库进行 **GraphQL** 集成 。
* 许多额外特性(归功于 Starlette),例 如:
* 从不同位置声明**参数**:**headers**、**cookies**、**表单字段**、 **文件**。
* 如何设置**校验约束**,比 如 `maximum_length` 或 `regex` 。
* 一个强大且好用的** < dfn title = "也称为:组件、资源、提供者、服务、可注入" > 依赖注入< / dfn > **系统。
* 安全与认证。包括 **OAuth2** (配合 **JWT tokens** )和 **HTTP Basic** 。
* 更高级(但一样简单)的**深度嵌套 JSON 模型**声明技巧(感谢 Pydantic)。
* **GraphQL** 集成,支持 [Strawberry ](https://strawberry.rocks ) 等库。
* 许多额外特性(感谢 Starlette),比 如:
* * *WebSockets**
* 基于 HTTPX 和 `pytest` 的极其简单的 测试
* 基于 HTTPX 和 `pytest` 的超简单 测试
* * *CORS**
* * *Cookie Sessions**
* ……以及更多 。
* ...等等 。
### 部署你的应用(可选) { #deploy -your-app-optional }
你可以选择 把 FastAPI 应用部署到 [FastAPI Cloud ](https://fastapicloud.com ),如果还没有的话去加入候补名单吧 。🚀
你可以把 FastAPI 应用部署到 [FastAPI Cloud ](https://fastapicloud.com )。还没有账号就去等候名单报名 。🚀
如果你已经有 **FastAPI Cloud** 账号(我们从候补名单邀请了你 😉),你可以用一个命令部署你的 应用。
如果你已经有 **FastAPI Cloud** 账号(我们从等候名单邀请了你 😉),只要一条命令就能部署 应用。
< div class = "termy" >
@ -510,76 +510,76 @@ Deploying to FastAPI Cloud...
< / div >
就这样!现在你可以通过该 URL 访问你的应用了。✨
就这些!现在用这个地址就能 访问你的应用了。✨
#### 关于 FastAPI Cloud { #about -fastapi-cloud }
**[FastAPI Cloud](https://fastapicloud.com)** 由 **FastAPI** 的同一位作者和团队打造 。
**[FastAPI Cloud](https://fastapicloud.com)** 出自 **FastAPI** 同一位作者和团队 。
它让你以最小的工作量就能**构建**、**部署**并 **访问**一个 API。
它让你以最小成本**构建**、**部署**、 **访问**一个 API。
它把用 FastAPI 构建应用时的**开发者体验**带到了部署到云上的过程 。🎉
把用 FastAPI 开发应用时的**开发者体验**,带到了**部署到云上**这一步 。🎉
FastAPI Cloud 是「FastAPI and friends」开源项目的主要赞助方和资金提供者 。✨
FastAPI Cloud 是「FastAPI and friends」开源项目的主要赞助方和资金来源 。✨
#### 部署到其他云厂商 { #deploy -to-other-cloud-providers }
FastAPI 是开源且基于标准的。你可以部署 FastAPI 应用 到你选择的 任意云厂商。
FastAPI 是开源且基于标准的。你可以部署到任意云厂商。
按照你的云厂商的指南部署 FastAPI 应用即可 。🤓
按照各家云厂商的指南部署 FastAPI 应用就行 。🤓
## 性能 { #performance }
独立机构 TechEmpower 的基准测试显示,运行在 Uvicorn 下的 **FastAPI** 应用是 [最快的 Python 框架之一 ](https://www.techempower.com/benchmarks/#section=test&runid=7464e520-0dc2-473d-bd34-dbdfd7e85911&hw=ph&test=query&l=zijzen-7 ),仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部使用 它们)。(*)
独立的 TechEmpower 基准测试显示,Uvicorn 下运行的 **FastAPI** 应用[是 Python 里最快的框架之一](https://www.techempower.com/benchmarks/#section=test& runid=7464e520-0dc2-473d-bd34-dbdfd7e85911& hw=ph& test=query& l=zijzen-7)。仅次于 Starlette 和 Uvicorn 本身(FastAPI 内部就用到 它们)。(*)
想了解更多,请参阅 [基准测试 ](https://fastapi.tiangolo.com/zh/benchmarks/ ) 章节 。
想了解更多,查看[基准测试](https://fastapi.tiangolo.com/zh/benchmarks/) 。
## 依赖项 { #dependencies }
## 依赖 { #dependencies }
FastAPI 依赖 Pydantic 和 Starlette。
### `standard` 依赖 { #standard -dependencies }
### `standard` 依赖组 { #standard -dependencies }
当你通过 `pip install "fastapi[standard]"` 安装 FastAPI 时,会包含 `standard` 组的一些 可选依赖:
用 `pip install "fastapi[standard]"` 安装时,会包含 `standard` 这 组可选依赖:
Pydantic 使 用:
Pydantic 用到 :
* [`email-validator` ](https://github.com/JoshData/python-email-validator ) - 用于 email 校验。
* [`email-validator` ](https://github.com/JoshData/python-email-validator ) —— 用于邮箱 校验。
Starlette 使 用:
Starlette 用到 :
* [`httpx` ](https://www.python-httpx.org ) - 使用 `TestClient` 时需要 。
* [`jinja2` ](https://jinja.palletsprojects.com ) - 使用默认模板配置时需要 。
* [`python-multipart` ](https://github.com/Kludex/python-multipart ) - 使用 `request.form()` 支持表单< dfn title = "将 HTTP 请求中的字符串转换为 Python 数据" > 「解析」</ dfn > 时需要 。
* [`httpx` ](https://www.python-httpx.org ) —— 想用 `TestClient` 就需要它 。
* [`jinja2` ](https://jinja.palletsprojects.com ) —— 想用默认模板配置就需要它 。
* [`python-multipart` ](https://github.com/Kludex/python-multipart ) —— 想 支持表单< dfn title = "把来自 HTTP 请求的字符串转换成 Python 数据" > "解析"</ dfn > ,即 `request.form()` ,就需要它 。
FastAPI 使 用:
FastAPI 用到 :
* [`uvicorn` ](https://www.uvicorn.dev ) - 加载并提供你的应用的服务器。包含 `uvicorn[standard]` ,其中包含高性能服务所需的一些依赖(例 如 `uvloop` )。
* `fastapi-cli[standard]` - 提供 `fastapi` 命令。
* 其中包含 `fastapi-cloud-cli` ,它允许你将 FastAPI 应用部署到 [FastAPI Cloud ](https://fastapicloud.com )。
* [`uvicorn` ](https://www.uvicorn.dev ) —— 负责加载和服务你的应用。包含 `uvicorn[standard]` ,内置一些高性能服务需要的依赖(比 如 `uvloop` )。
* `fastapi-cli[standard]` —— 提供 `fastapi` 命令。
* 其中包含 `fastapi-cloud-cli` ,可把 应用部署到 [FastAPI Cloud ](https://fastapicloud.com )。
### 不包含 `standard` 依赖 { #without -standard-dependencies }
如果你不想包含这些 `standard` 可选依赖,可以使 用 `pip install fastapi` ,而不是 `pip install "fastapi[standard]"` 。
如果不想带上 `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]"` 。
如果你想安装标准依赖,但去掉 `fastapi-cloud-cli` ,可以 用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"` 。
### 其他 可选依赖 { #additional -optional-dependencies }
### 额外 可选依赖 { #additional -optional-dependencies }
还有一些你可能想安装的可选 依赖。
还有一些你可能会用到的额外 依赖。
额外的 Pydantic 可选依赖:
Pydantic 的 可选依赖:
* [`pydantic-settings` ](https://docs.pydantic.dev/latest/usage/pydantic_settings/ ) - 用于配置管理 。
* [`pydantic-extra-types` ](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/ ) - 用于在 Pydantic 中使用的额外 类型。
* [`pydantic-settings` ](https://docs.pydantic.dev/latest/usage/pydantic_settings/ ) —— 管理配置 。
* [`pydantic-extra-types` ](https://docs.pydantic.dev/latest/usage/types/extra_types/extra_types/ ) —— 更多可用于 Pydantic 的 类型。
额外的 FastAPI 可选依赖:
FastAPI 的 可选依赖:
* [`orjson` ](https://github.com/ijl/orjson ) - 使用 `ORJSONResponse` 时需要 。
* [`ujson` ](https://github.com/esnme/ultrajson ) - 使用 `UJSONResponse` 时需要 。
* [`orjson` ](https://github.com/ijl/orjson ) —— 想用 `ORJSONResponse` 就需要它 。
* [`ujson` ](https://github.com/esnme/ultrajson ) —— 想用 `UJSONResponse` 就需要它 。
## 许可协议 { #license }
## 许可证 { #license }
该项目遵循 MIT 许可协议 。
本项目使用 MIT 许可证 。