Python FastAPI 教學:從零建立 REST API 完整指南
為什麼選擇 FastAPI
如果你在 2026 年還在猶豫要用哪個 Python Web 框架來建 REST API,我會毫不猶豫地推薦 FastAPI。為什麼?三個字:快、穩、爽。
FastAPI 基於 Starlette 和 Pydantic 打造,效能直逼 Node.js 和 Go,在各大 benchmark 中名列前茅。但真正讓它脫穎而出的是原生支援 Python type hints——你寫的型別標注不只是給 IDE 看的,它同時驅動了資料驗證和自動產生 API 文件。
簡單說,你寫一份程式碼,FastAPI 幫你做三件事:路由處理、資料檢查、文件產生。這個開發體驗一旦用過就回不去了。
環境安裝與專案建立
開始之前,確認你的 Python 版本在 3.9 以上。接著用以下指令建立專案:
mkdir fastapi-todo && cd fastapi-todo
python -m venv venv
source venv/bin/activate # Windows 用 venv\Scripts\activate
pip install fastapi uvicorn
建立主要檔案 main.py:
from fastapi import FastAPI
app = FastAPI(title="Todo API", version="1.0.0")
@app.get("/")
def root():
return {"message": "歡迎使用 Todo API!"}
啟動開發伺服器:
uvicorn main:app --reload
打開瀏覽器訪問 http://127.0.0.1:8000,看到 JSON 回應就代表你的 FastAPI 已經跑起來了。--reload 參數會在你修改程式碼時自動重啟,開發時超方便。
第一個 API 端點
REST API 的核心就是定義端點。FastAPI 用裝飾器讓這件事變得極其簡單:
from fastapi import FastAPI
app = FastAPI()
# GET 端點 - 取得所有待辦事項
@app.get("/todos")
def get_todos():
return [
{"id": 1, "title": "學 FastAPI", "done": False},
{"id": 2, "title": "建立 REST API", "done": False}
]
# POST 端點 - 新增待辦事項
@app.post("/todos")
def create_todo(title: str):
return {"id": 3, "title": title, "done": False}
注意到沒?GET 和 POST 就是換一個裝飾器的事,路徑參數和查詢參數都能自動解析。FastAPI 會根據函式簽名推斷參數來源——路徑中的變數是路徑參數,其他就是查詢參數。
Pydantic 資料驗證
真實世界的 API 不能只靠簡單的參數,你需要結構化的資料驗證。這就是 Pydantic 大顯身手的地方:
from pydantic import BaseModel, Field
from typing import Optional
class TodoCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
description: Optional[str] = None
priority: int = Field(default=1, ge=1, le=5)
class TodoResponse(BaseModel):
id: int
title: str
description: Optional[str]
priority: int
done: bool = False
定義好 Model 後,在端點函式中直接使用:
@app.post("/todos", response_model=TodoResponse)
def create_todo(todo: TodoCreate):
new_todo = {
"id": 1,
"title": todo.title,
"description": todo.description,
"priority": todo.priority,
"done": False
}
return new_todo
當有人送了一個空的 title 或 priority 超過 5 的請求,FastAPI 會自動回傳 422 錯誤和清楚的錯誤訊息。你不用自己寫任何驗證邏輯,全部交給 Pydantic 就好。
CRUD 完整範例
讓我們把 Todo API 做完整,包含新增、查詢、更新、刪除四個操作:
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field
from typing import Optional
app = FastAPI(title="Todo CRUD API")
# 用記憶體存資料(正式環境請用資料庫)
todos: dict[int, dict] = {}
counter = 0
class TodoCreate(BaseModel):
title: str = Field(..., min_length=1, max_length=100)
description: Optional[str] = None
class TodoUpdate(BaseModel):
title: Optional[str] = None
description: Optional[str] = None
done: Optional[bool] = None
# Create
@app.post("/todos", status_code=201)
def create_todo(todo: TodoCreate):
global counter
counter += 1
todos[counter] = {
"id": counter,
"title": todo.title,
"description": todo.description,
"done": False
}
return todos[counter]
# Read all
@app.get("/todos")
def list_todos(done: Optional[bool] = None):
results = list(todos.values())
if done is not None:
results = [t for t in results if t["done"] == done]
return results
# Read one
@app.get("/todos/{todo_id}")
def get_todo(todo_id: int):
if todo_id not in todos:
raise HTTPException(status_code=404, detail="找不到該待辦事項")
return todos[todo_id]
# Update
@app.patch("/todos/{todo_id}")
def update_todo(todo_id: int, updates: TodoUpdate):
if todo_id not in todos:
raise HTTPException(status_code=404, detail="找不到該待辦事項")
for key, value in updates.model_dump(exclude_unset=True).items():
todos[todo_id][key] = value
return todos[todo_id]
# Delete
@app.delete("/todos/{todo_id}", status_code=204)
def delete_todo(todo_id: int):
if todo_id not in todos:
raise HTTPException(status_code=404, detail="找不到該待辦事項")
del todos[todo_id]
幾個重點:HTTPException 用來處理錯誤情境、status_code 設定回傳的 HTTP 狀態碼、model_dump(exclude_unset=True) 讓 PATCH 更新時只處理有傳入的欄位。這個模式在實務上非常實用。
如果你正在做自動化相關的專案,可以參考Python 排程自動化教學,把定時任務和 API 結合使用效果更好。
自動生成 API 文件
這是 FastAPI 最讓人驚豔的功能——啟動伺服器後,直接訪問這兩個網址:
- Swagger UI:
http://127.0.0.1:8000/docs— 互動式 API 文件,可以直接在頁面上測試 - ReDoc:
http://127.0.0.1:8000/redoc— 漂亮的唯讀文件,適合分享給前端同事
你不需要寫任何額外的設定,FastAPI 根據你的 type hints、Pydantic models、docstring 自動產生符合 OpenAPI 標準的文件。前端工程師看到這個文件,就能直接開始串接,不用再開會對規格了。
想讓文件更完整,可以在路由加上描述:
@app.post("/todos", status_code=201, summary="建立待辦事項",
description="建立一個新的待辦事項,title 為必填欄位")
def create_todo(todo: TodoCreate):
...
部署與下一步
開發完成後,部署 FastAPI 有幾個推薦做法:
# 建立 requirements.txt
pip freeze > requirements.txt
# 正式環境用 gunicorn + uvicorn worker
pip install gunicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000
部署平台方面,2026 年最方便的選擇是 Railway、Fly.io 或 Docker + 雲端。如果你的 API 需要處理大量請求,用 Docker 容器搭配 Kubernetes 會是更穩定的方案。
學會 FastAPI 基礎之後,建議你接著探索這些進階主題:
- 接上真正的資料庫(SQLAlchemy + PostgreSQL)
- 加上 JWT 認證和權限控制
- 用 Background Tasks 處理耗時操作
- WebSocket 即時通訊
如果你對用 Python 做自動化也有興趣,推薦看看Python Selenium 爬蟲教學,兩者搭配可以打造完整的資料收集與 API 服務系統。
你可能也喜歡
探索其他領域的精選好文