@ -1,5 +1,11 @@
# FastAPI { #fastapi }
< style >
.md-content .md-typeset h1 { display: none; }
< / style >
< p align = "center" >
< a href = "https://fastapi.tiangolo.com" > < img src = "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt = "FastAPI" > < / a >
< a href = "https://fastapi.tiangolo.com/zh-hant " > < img src = "https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" alt = "FastAPI" > < / a >
< / p >
< p align = "center" >
< em > FastAPI 框架,高效能,易於學習,快速開發,適用於生產環境< / em >
@ -21,138 +27,140 @@
---
**文件**: < a href = "https://fastapi.tiangolo.com" target = "_blank" > https://fastapi.tiangolo.com< / a >
**文件**: < a href = "https://fastapi.tiangolo.com/zh-hant " target = "_blank" > https://fastapi.tiangolo.com/zh-hant < / a >
**程式碼**: < a href = "https://github.com/fastapi/fastapi" target = "_blank" > https://github.com/fastapi/fastapi< / a >
---
FastAPI 是一個現代、快速(高效能)的 web 框架,用於 Python 並採用標準 Python 型別提示 。
FastAPI 是一個現代、快速(高效能)的 Web 框架,用於以 Python 並基於標準的 Python 型別提示來構建 API 。
主要特點包含:
- **快速** : 非常高的效能,可與 **NodeJS** 和 **Go** 效能相當 (歸功於 Starlette and Pydantic)。 [FastAPI 是最快的 Python web 框架之一 ](#performance )。
- **極速開發** : 提高開發功能的速度約 200% 至 300%。 \ *
- **更少的 Bug** : 減少約 40% 的人為(開發者)導致的錯誤。 \ *
- **直覺** : 具有出色的編輯器支援,處處都有 < abbr title = "也被稱為自動完成、IntelliSense" > 自動補全</ abbr > 以減少 偵錯時間。
- **簡單** : 設計上易於使用和學習,大幅減少閱讀文件的 時間。
- **簡潔** : 最小化程式碼重複性。可以通過不同的參數聲明來實現更豐富的功能,和 更少的錯誤。
- **穩健** : 立即獲得生產級可用的程式碼,還有 自動生成互動式文件。
- **標準化** : 基於 (且完全相容於) OpenAPIs 的相關 標準:< 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 > 。
* **快速** :非常高的效能,可與 **NodeJS** 和 **Go** 相當(歸功於 Starlette 和 Pydantic)。[最快的 Python 框架之一](#performance )。
* **極速開發** :開發功能的速度可提升約 200% 至 300%。 *
* **更少的 Bug** :減少約 40% 的人為(開發者)錯誤。 *
* **直覺** :具有出色的編輯器支援,處處都有 < abbr title = "也被稱為: 自動完成、自動補全、 IntelliSense" > 自動補全</ abbr > 。更少的 偵錯時間。
* **簡單** :設計上易於使用與學習。更少的讀文件 時間。
* **簡潔** :最小化程式碼重複性。每個參數宣告可帶來多個功能。 更少的錯誤。
* **穩健** :立即獲得可投入生產的程式碼,並 自動生成互動式文件。
* **標準化** :基於(且完全相容於)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 -->
{% if sponsors %}
### 基石贊助商 { #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" > 其他贊助商< / a >
< a href = "https://fastapi.tiangolo.com/zh-hant/ 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 > Microsoft< / strong > < a href = "https://github.com/fastapi/fastapi/pull/26" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
"_我們使用 **FastAPI** 來建立產生**預測**結果的 **REST** 伺服器。 [for Ludwig]_"
"_我們採用了 **FastAPI** 函式庫來啟動一個 **REST** 伺服器,供查詢以取得**預測**。 [for Ludwig]_"
< 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/" 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 > podcast host < / strong > < a href = "https://x.com/brianokken/status/1112220079972728832" target = "_blank" > < small > (ref)< / small > < / a > < / div >
< 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 > podcast 主持人 < / strong > < a href = "https://x.com/brianokken/status/1112220079972728832" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
"_老實說,你建造的東西看起來非常堅固和精緻。在很多方面,這就是我想要的,看到有人建造它 真的很鼓舞人心。_"
"_老實說,你們做的看起來非常穩健又精緻。很多方面都正是我希望 **Hug** 成為的樣子——看到有人把它建出來 真的很鼓舞人心。_"
< div style = "text-align: right; margin-right: 10%;" > Timothy Crosley - < strong > < a href = "https://github.com/hugapi/hug" target = "_blank" > Hug< / a > creator < / strong > < a href = "https://news.ycombinator.com/item?id=19455465" target = "_blank" > < small > (ref)< / small > < / a > < / div >
< 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** [...] 它很快、易用、也容易 學習 [...]_"
"_我們的 **APIs ** 已經改用 **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 > creators < / 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 >
< 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 >
---
"_如果有人想要建立一個生產環境 的 Python API,我強烈推薦 **FastAPI** ,它**設計精美**,**使用簡單**且**高度可擴充**,它已成為我們 API 優先開發策略中的**關鍵組件**,並且驅動了許多自動化 服務,例如我們的 Virtual TAC Engineer。_"
"_如果有人想要建立一個可投入 生產的 Python API,我強烈推薦 **FastAPI** 。它**設計精美**、**使用簡單**且**高度可擴充**,已成為我們 API 優先開發策略中的**關鍵組件**,推動了許多自動化與 服務,例如我們的 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/" target = "_blank" > < small > (ref)< / small > < / a > < / div >
---
## **Typer** ,命令列中的 FastAPI
< 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 >
## FastAPI 迷你紀錄片 { #fastapi -mini-documentary }
如果你不是在開發網頁 API,而是正在開發一個在終端機中運行的< abbr title = "Command Line Interface" > 命令列< / abbr > 應用程式,不妨嘗試 < a href = "https://typer.tiangolo.com/ " class = "external-link" target = "_blank" > **Typer** < / a > 。
在 2025 年底發布了一支 < a href = "https://www.youtube.com/watch?v=mpR8ngthqiE" class = "external-link" target = "_blank" > FastAPI 迷你紀錄片< / a > ,你可以在線上觀看:
**Typer** 是 FastAPI 的小兄弟。他立志成為命令列的 **FastAPI** 。 ⌨️ 🚀
< 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 >
## 安裝需求
## **Typer** ,命令列的 FastAPI { #typer -the-fastapi-of-clis }
FastAPI 是站在以下巨人的肩膀上:
< 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 >
- < a href = "https://www.starlette.dev/" class = "external-link" target = "_blank" > Starlette< / a > 負責網頁的部分
- < a href = "https://docs.pydantic.dev/" class = "external-link" target = "_blank" > Pydantic< / a > 負責資料的部分
如果你不是在做 Web API,而是要建立一個在終端機中使用的 < abbr title = "Command Line Interface - 命令列介面" > CLI< / abbr > 應用程式,可以看看 < a href = "https://typer.tiangolo.com/" class = "external-link" target = "_blank" > **Typer**< / a > 。
## 安裝
**Typer** 是 FastAPI 的小老弟。他立志成為命令列世界的 **FastAPI** 。⌨️ 🚀
< div class = "termy" >
## 需求 { #requirements }
```console
$ pip install fastapi
FastAPI 是站在以下巨人的肩膀上:
---> 100%
```
* < 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 > 負責資料部分。
< / div >
## 安裝 { #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-hant/virtual-environments/ " class = "external-link" target = "_blank" > 虛擬環境 < / a > ,然後安裝 FastAPI:
< div class = "termy" >
```console
$ pip install "uvicorn [standard]"
$ pip install "fastapi [standard]"
---> 100%
```
< / div >
## 範例
**注意**:請務必將 `"fastapi[standard]"` 用引號包起來,以確保在所有終端機中都能正常運作。
### 建立
## 範例 { #example }
- 建立一個 python 檔案 `main.py` ,並寫入以下程式碼:
### 建立 { #create -it }
```Python
from typing import Union
建立檔案 `main.py` ,內容如下:
```Python
from fastapi import FastAPI
app = FastAPI()
@ -164,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` :
< summary > 或使用 < code > async def< / code > ...< / summary >
```Python hl_lines="9 14"
from typing import Union
如果你的程式碼使用 `async` / `await` ,請使用 `async def` :
```Python hl_lines="7 12"
from fastapi import FastAPI
app = FastAPI()
@ -187,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}
```
**注意**:
如果你不知道是否會用到,可以查看 _"In a hurry?"_ 章節中,關於 < a href = "https://fastapi.tiangolo.com/async/#in-a-hurry" target = "_blank" > `async` 和 `await` 的部分 </ a > 。
如果你不確定,請查看文件中 _"In a hurry?"_ 章節的 < a href = "https://fastapi.tiangolo.com/zh-hant/ 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.
```
@ -216,21 +235,21 @@ 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-hant/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 > 。
你將會看到以下的 JSON 回應:
你將會看到以下 JSON 回應:
```JSON
{"item_id": 5, "q": "somequery"}
@ -238,36 +257,34 @@ INFO: Application startup complete.
你已經建立了一個具有以下功能的 API:
- 透過路徑 `/` 和 `/items/{item_id}` 接受 HTTP 請求。
- 以上路經 都接受 `GET` < em > 請求 </ em > (也被稱為 HTTP _方法_ )。
- 路徑 `/items/{item_id}` 有一個 `int` 型別的 `item_id` 參數 。
- 路徑 `/items/{item_id}` 有一個 `str` 型別的 查詢參數 `q` 。
* 透過路徑 `/` 和 `/items/{item_id}` 接受 HTTP 請求。
* 以上兩個路徑 都接受 `GET` < em > 操作 </ em > (也被稱為 HTTP _方法_ )。
* 路徑 `/items/{item_id}` 有一個 `int` 型別的路徑參數 `item_id` 。
* 路徑 `/items/{item_id}` 有一個可選的 `str` 查詢參數 `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 > 。
接著前往 < 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 > 提供 ):

### ReDoc 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 > 。
你將看到 ReDoc 文件 ( 由 < 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` 檔案,來接收一個帶有 body 的 `PUT` 請求 。
現在修改 `main.py` 檔案,使其能從 `PUT` 請求接收 body 。
我們使用 Pydantic 來使用標準的 Python 型別聲明請求。
```Python hl_lines="4 9-12 25-27"
from typing import Union
多虧了 Pydantic,你可以用標準的 Python 型別來宣告 body。
```Python hl_lines="2 7-10 23-25"
from fastapi import FastAPI
from pydantic import BaseModel
@ -277,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("/")
@ -286,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}
@ -295,43 +312,43 @@ 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 文件會自動更新,並加入新的 body 請求 :
* 互動式 API 文件會自動更新,包含新的 body :

- 點擊 "Try it out" 按鈕, 你可以填寫參數並直接與 API 互動:
* 點擊「Try it out」按鈕, 你可以填寫參數並直接與 API 互動:

- 然後點擊 "Execute" 按鈕,使用者介面將會向 API 發送請求,並將結果 顯示在螢幕上:
* 然後點擊「Execute」按鈕,使用者介面會與你的 API 溝通、送出參數、取得結果並 顯示在螢幕上:

### ReDoc API 文件升級
### 替代 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 > 。
- ReDoc API 文件會自動更新,並加入新的參數和 body 請求 :
* 替代文件也會反映新的查詢參數與 body :

### 總結
### 總結 { #recap }
總結來說, 你就像宣告函式的參數型別一樣,只宣告了一次請求參數和請求主體參數等 型別。
總結來說,你只需在函式參數中**一次**宣告參數、body 等的 型別。
你使用 Python 標準 型別來完成聲明 。
你使用的是現代標準的 Python 型別。
你不需要學習新的語法、類別、方法或函式庫 等等。
你不需要學新的語法、特定函式庫的方法或類別, 等等。
只需要使用 **Python 以上的版本 ** 。
就用標準的 **Python ** 。
舉個範例,比如宣告 int 的型別 :
例如,對於一個 `int` :
```Python
item_id: int
@ -343,126 +360,200 @@ item_id: int
item: Item
```
在進行一次宣告後 ,你將獲得:
- 編輯器支援 :
- 自動補全
- 型別檢查
- 資料驗證:
- 驗證失敗時自動生成清楚的錯誤訊息
- 可驗證多層巢狀的 JSON 物件
- < abbr title = "也被稱為: 序列化或解析 " > 轉換< / abbr > 輸入的資料: 轉換來自網路請求到 Python 資料型別。包含以下數據 :
- JSON
- 路徑參數
- 查詢參數
- Cookies
- 請求標頭
- 表單
- 文件
- < abbr title = "也被稱為: 序列化或解析 " > 轉換< / abbr > 輸出的資料: 轉換 Python 資料型別到網路傳輸的 JSON :
- 轉換 Python 型別 (`str`、 `int` 、 `float` 、 `bool` 、 `list` 等)
- `datetime` 物件
- `UUID` 物件
- 數據模型
- ...還有其他更多
- 自動生成的 API 文件,包含 2 種不同的使用 介面:
- Swagger UI
- ReDoc
…透過一次宣告 ,你將獲得:
* 編輯器支援,包括 :
* 自動補全。
* 型別檢查。
* 資料驗證:
* 當資料無效時,自動且清楚的錯誤。
* 即使是深度巢狀的 JSON 物件也能驗證。
* 輸入資料的 < abbr title = "也被稱為:序列化、解析、封送 " > 轉換< / abbr > :從網路讀入到 Python 資料與型別。包含 :
* JSON。
* 路徑參數。
* 查詢參數。
* Cookies。
* 標頭。
* 表單。
* 檔案。
* 輸出資料的 < abbr title = "也被稱為:序列化、解析、封送 " > 轉換< / abbr > :從 Python 資料與型別轉換為網路資料(JSON) :
* 轉換 Python 型別(`str`、`int`、`float`、`bool`、`list` 等)。
* `datetime` 物件。
* `UUID` 物件。
* 資料庫模型。
* ...還有更多。
* 自動生成的互動式 API 文件,包含 2 種替代的使用者 介面:
* 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` 範例的請求 body) 。
- 對於 `PUT` 的請求 `/items/{item_id}` ,將會讀取 body 為 JSON :
- 驗證是否有必填屬性 `name` 且型別是 `str` 。
- 驗證是否有必填屬性 `price` 且型別是 `float` 。
- 驗證是否有選填屬性 `is_offer` 且型別是 `bool` 。
- 以上驗證都適用於多層次巢狀 JSON 物件。
- 自動轉換 JSON 格式 。
- 透過 OpenAPI 文件來記錄所有內容,可以被 用於:
- 互動式文件系統。
- 自動為多種程式語言生成用戶端的程式碼 。
- 提供兩種交互式文件 介面。
回到前面的程式碼範例,**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` 時的 body) 。
* 對於 `/items/{item_id}` 的 `PUT` 請求,以 JSON 讀取 body :
* 檢查是否有必填屬性 `name` ,且為 `str` 。
* 檢查是否有必填屬性 `price` ,且為 `float` 。
* 檢查是否有可選屬性 `is_offer` ,若存在則應為 `bool` 。
* 以上也適用於深度巢狀的 JSON 物件。
* 自動在 JSON 與 Python 之間轉換 。
* 以 OpenAPI 記錄所有內容,可 用於:
* 互動式文件系統。
* 為多種語言自動產生用戶端程式碼的系統 。
* 直接提供兩種互動式文件網頁 介面。
---
雖然我們只敘述了表面的功能,但其實你已經理解了它是如何執行 。
我們只觸及了表面,但你已經了解它的運作方式了 。
試著修改以下程式碼 :
試著把這一行 :
```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/tutorial/" > 教學 - 使用者指南< / a > 。
若想看包含更多功能的完整範例,請參考 < a href = "https://fastapi.tiangolo.com/zh-hant/tutorial/" > 教學 - 使用者指南< / a > 。
**劇透警告**:教學 - 使用者指南包含:
* 來自不同來源的**參數**宣告:例如 **headers** 、**cookies**、**form fields** 和 **files** 。
* 如何設定**驗證限制**,如 `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**
* 基於 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 開發應用的**開發者體驗**帶到**部署**到雲端的流程中。🎉
FastAPI Cloud 是「FastAPI 與好朋友們」這些開源專案的主要贊助與資金來源。✨
#### 部署到其他雲端供應商 { #deploy -to-other-cloud-providers }
FastAPI 是開源且基於標準。你可以把 FastAPI 應用部署到任何你選擇的雲端供應商。
依照你雲端供應商的指南來部署 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-hant/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 > - 用於電子郵件驗證。
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 > - 若要支援表單 < abbr title = "將來自 HTTP 請求的字串轉換為 Python 資料" > "解析"</ abbr > ,搭配 `request.form()` 。
- 對來自不同地方的**參數**進行宣告:像是 **headers** , **cookies** , **form 表單**以及**上傳檔案** 。
- 如何設定 **驗證限制** 像是 `maximum_length` or `regex` 。
- 簡單且非常容易使用的 ** < abbr title = "也被稱為元件、資源、提供者、服務或是注入" > 依賴注入</ abbr > ** 系統。
- 安全性和身份驗證,包含提供支援 **OAuth2** 、**JWT tokens** 和 **HTTP Basic** 驗證。
- 更進階 (但同樣簡單) 的宣告 **多層次的巢狀 JSON 格式** (感謝 Pydantic)。
- **GraphQL** 與 < a href = "https://strawberry.rocks" class = "external-link" target = "_blank" > Strawberry</ a > 以及其他的相關函式庫進行整合。
- 更多其他的功能 (感謝 Starlette) 像是:
- **WebSockets**
- 於 HTTPX 和 `pytest` 的非常簡單測試
- **CORS**
- **Cookie Sessions**
- ...以及更多
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 > 。
來自獨立機構 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 的底層)。 (\*)
### 不含 `standard` 依賴套件 { #without -standard-dependencies }
想了解更多訊息,可以參考 < a href = "https://fastapi.tiangolo.com/benchmarks/" class = "internal-link" target = "_blank" > 測試結果< / a > 。
如果你不想包含 `standard` 可選依賴,可以改用 `pip install fastapi` (而不是 `pip install "fastapi[standard]"` )。
## 可選的依賴套件
### 不含 `fastapi-cloud-cli` { #without -fastapi-cloud-cli }
用於 Pydantic:
如果你想安裝帶有 standard 依賴、但不包含 `fastapi-cloud-cli` ,可以使用 `pip install "fastapi[standard-no-fastapi-cloud-cli]"` 。
- < a href = "https://github.com/JoshData/python-email-validator" target = "_blank" > < code > email-validator< / code > < / a > - 用於電子郵件驗證。
- < 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 一起使用的額外型別。
### 額外可選依賴套件 { #additional -optional-dependencies }
用於 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 > 時安裝。
- < 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,可能不需要它)。
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 許可協議。
本專案以 MIT 授權條款釋出 。