01-1. FastAPI 是什麼?為什麼選擇它?

⏱️ 閱讀時間: 10 分鐘 🎯 難度: ⭐ (入門)


🤔 一句話解釋

FastAPI 是一個現代、高效能的 Python Web 框架,專門用來建立 API,速度可以媲美 Node.js 和 Go。


🏎️ 用賽車來比喻

想像你要參加一場 API 框架大賽:

Django = 豪華房車

# Django 內建超多功能
from django.contrib.auth.models import User
from django.contrib.admin import site
from django.contrib.sessions.middleware import SessionMiddleware
# ... 還有 ORM、模板引擎、Admin 後台等等

特點:

  • 🚗 功能齊全,開箱即用
  • 🚗 適合完整的 Web 應用
  • ⚠️ 有點重,起步較慢
  • ⚠️ 學習曲線較高

Flask = 機車

# Flask 極簡
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello():
    return 'Hello!'

特點:

  • 🏍️ 輕量靈活
  • 🏍️ 自由度高
  • ⚠️ 需要自己裝配零件
  • ⚠️ 沒有內建驗證、文件

FastAPI = 超跑 🏎️

# FastAPI = 快 + 現代化
from fastapi import FastAPI
app = FastAPI()

@app.get('/')
async def hello():
    return {'message': 'Hello!'}

特點:

  • 🏎️ 極速 - 效能媲美 Go/Node.js
  • 🏎️ 自動文件 - Swagger UI 開箱即用
  • 🏎️ 型別安全 - 完整 Type Hints 支援
  • 🏎️ 資料驗證 - Pydantic 自動驗證
  • 🏎️ 非同步 - 原生 async/await 支援

📊 效能比較

根據 TechEmpower 基準測試:

框架效能排名(越高越好):

Starlette (FastAPI 底層)  ████████████████████  100%
FastAPI                   ███████████████████   95%
Node.js (Express)         ████████████████      80%
Flask                     ████████              40%
Django                    ██████                30%

為什麼 FastAPI 這麼快?

# 1. 基於 Starlette(高效能 ASGI 框架)
from starlette.applications import Starlette

# 2. 使用 Pydantic(Rust 編譯的驗證引擎)
from pydantic import BaseModel

# 3. 原生非同步支援
async def get_data():
    result = await database.fetch()  # 不會阻塞!
    return result

🎯 FastAPI 的核心優勢

1. 自動生成 API 文件

當你寫好 API,文件就自動生成了!

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI(
    title="我的 API",
    description="這是一個很棒的 API",
    version="1.0.0"
)

class User(BaseModel):
    name: str
    email: str
    age: int

@app.post("/users/", response_model=User)
async def create_user(user: User):
    """
    建立新使用者

    - **name**: 使用者名稱
    - **email**: 電子郵件
    - **age**: 年齡(必須大於 0)
    """
    return user

啟動後訪問:

  • http://localhost:8000/docs → Swagger UI
  • http://localhost:8000/redoc → ReDoc

自動產生的文件包含:

  • ✅ 所有 API 端點
  • ✅ 請求/回應格式
  • ✅ 資料型別
  • ✅ 線上測試功能

2. 自動資料驗證

不用自己寫驗證邏輯!

from fastapi import FastAPI
from pydantic import BaseModel, EmailStr, Field

app = FastAPI()

class UserCreate(BaseModel):
    name: str = Field(..., min_length=2, max_length=50)
    email: EmailStr
    age: int = Field(..., ge=0, le=150)  # 0 <= age <= 150

@app.post("/users/")
async def create_user(user: UserCreate):
    # 如果資料不符合規則,FastAPI 自動返回 422 錯誤
    # 你不用寫任何驗證代碼!
    return {"message": f"歡迎 {user.name}!"}

錯誤的請求:

POST /users/
{
    "name": "A",
    "email": "not-an-email",
    "age": -5
}

自動回應:

{
    "detail": [
        {
            "loc": ["body", "name"],
            "msg": "String should have at least 2 characters",
            "type": "string_too_short"
        },
        {
            "loc": ["body", "email"],
            "msg": "value is not a valid email address",
            "type": "value_error.email"
        },
        {
            "loc": ["body", "age"],
            "msg": "Input should be greater than or equal to 0",
            "type": "greater_than_equal"
        }
    ]
}

3. 完整的 Type Hints 支援

IDE 自動補全、錯誤提示都靠它!

from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

@app.get("/items/{item_id}")
async def get_item(item_id: int) -> Item:  # 返回型別標註
    # IDE 知道 item_id 是 int
    # IDE 知道要返回 Item
    return Item(name="手機", price=999.99)

好處:

  • ✅ IDE 自動補全
  • ✅ 編譯時期錯誤檢查
  • ✅ 程式碼更易讀
  • ✅ 重構更安全

4. 原生非同步支援

處理 I/O 密集任務超高效!

from fastapi import FastAPI
import httpx

app = FastAPI()

# 同步版本(傳統)
@app.get("/sync")
def get_data_sync():
    # 等待 API 回應時,整個程序都在等待 😴
    response = httpx.get("https://api.example.com/data")
    return response.json()

# 非同步版本(推薦)
@app.get("/async")
async def get_data_async():
    async with httpx.AsyncClient() as client:
        # 等待時可以處理其他請求! 🚀
        response = await client.get("https://api.example.com/data")
        return response.json()

差異:

同步處理(每次 1 個):
請求 1: ████████████████████ 完成
請求 2:                      ████████████████████ 完成
請求 3:                                          ████████████████████ 完成
總時間: ═══════════════════════════════════════════════════════════════

非同步處理(同時多個):
請求 1: ████████████████████ 完成
請求 2: ████████████████████ 完成
請求 3: ████████████████████ 完成
總時間: ═════════════════════

🔄 FastAPI vs Django vs Flask

特性FastAPIDjangoFlask
效能⭐⭐⭐⭐⭐ 極高⭐⭐⭐ 中等⭐⭐⭐ 中等
學習曲線⭐⭐ 簡單⭐⭐⭐⭐ 複雜⭐ 極簡
自動文件✅ 內建❌ 需 DRF❌ 需擴展
型別提示✅ 完整支援⚠️ 部分⚠️ 部分
非同步✅ 原生支援⚠️ Django 4.1+❌ 需擴展
ORM❌ 自選✅ Django ORM❌ 自選
Admin 後台❌ 需自建✅ 內建❌ 需自建
適合場景API 服務全端應用小型應用/原型

🤔 什麼時候該選 FastAPI?

✅ 適合使用 FastAPI

  1. 建立 REST API / GraphQL API

    # 純 API 服務,沒有網頁渲染
    @app.get("/api/users")
    async def get_users():
        return users
  2. 微服務架構

    前端 SPA → API Gateway → FastAPI 服務 A
                           → FastAPI 服務 B
                           → FastAPI 服務 C
  3. 高效能需求

    • 即時系統
    • 高併發 API
    • 資料處理管線
  4. 機器學習模型服務

    @app.post("/predict")
    async def predict(data: InputData):
        result = model.predict(data)
        return {"prediction": result}

❌ 不太適合 FastAPI

  1. 需要 Admin 後台 → Django 更適合
  2. 傳統網頁應用(SSR) → Django/Flask 更適合
  3. 已有 Django 團隊 → 繼續用 Django + DRF
  4. 需要大量第三方套件支援 → Django 生態系更完整

🚀 FastAPI 背後的技術棧

┌─────────────────────────────────────────┐
│              你的 FastAPI 應用           │
├─────────────────────────────────────────┤
│  FastAPI(路由、依賴注入、OpenAPI 生成) │
├─────────────────────────────────────────┤
│  Pydantic(資料驗證、序列化)            │
├─────────────────────────────────────────┤
│  Starlette(ASGI 框架、中介軟體)        │
├─────────────────────────────────────────┤
│  Uvicorn(ASGI 伺服器)                  │
└─────────────────────────────────────────┘

關鍵元件

  1. Uvicorn - ASGI 伺服器(跑你的應用)
  2. Starlette - Web 框架核心(處理請求/回應)
  3. Pydantic - 資料驗證(確保資料正確)
  4. FastAPI - 整合以上所有 + 自動文件

✅ 重點總結

FastAPI 是什麼?

  1. 現代 Python Web 框架:專為 API 開發設計
  2. 高效能:基於 Starlette,效能媲美 Go/Node.js
  3. 開發者友善:自動文件、型別提示、資料驗證

為什麼選擇 FastAPI?

需求FastAPI 解決方案
寫文件好麻煩自動生成 OpenAPI 文件
驗證資料很煩Pydantic 自動驗證
IDE 沒提示完整 Type Hints 支援
效能不夠原生非同步 + 高效能
API 測試困難Swagger UI 線上測試

適合什麼場景?

  • ✅ REST API 服務
  • ✅ 微服務架構
  • ✅ 高效能 API
  • ✅ ML 模型服務
  • ⚠️ 不適合需要 Admin 後台的全端應用

🎤 面試這樣答

Q: 為什麼選擇 FastAPI 而不是 Flask 或 Django?

答案模板:

我選擇 FastAPI 主要基於三個考量:

  1. 效能需求:FastAPI 基於 Starlette,效能是 Flask 的 2-3 倍,對於高併發的 API 服務來說非常重要。

  2. 開發效率:FastAPI 自動生成 OpenAPI 文件和 Swagger UI,加上 Pydantic 的自動驗證,可以減少大量樣板程式碼。

  3. 型別安全:FastAPI 完整支援 Type Hints,配合 IDE 可以在開發階段就發現錯誤,減少 runtime 錯誤。

當然,如果專案需要完整的 Admin 後台或是已經有 Django 團隊,我會考慮使用 Django REST Framework。


🤓 小測驗

  1. FastAPI 的效能為什麼這麼好?

  2. FastAPI 的自動文件在哪裡查看?

  3. FastAPI 適合什麼場景?


下一篇: 01-2. 環境設定與第一個 API


最後更新:2025-12-17

0%