FastAPI 概述
FastAPI 是現代、快速 (高效能) 的 Python Web 框架,基於 Starlette 和 Pydantic,支援自動生成 API 文件 (OpenAPI)。
from fastapi import FastAPI
app = FastAPI(title="我的 API", version="1.0.0")
@app.get("/")
async def root():
return {"message": "Hello World"}
路徑與查詢參數
FastAPI 自動從路徑和查詢字串中提取參數,並進行型別驗證。
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = ""):
return {"item_id": item_id, "q": q}
請求體與 Pydantic
使用 Pydantic 模型定義請求體,自動進行資料驗證。
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
tax: float | None = None
@app.post("/items/")
async def create_item(item: Item):
return item
依賴注入與錯誤處理
FastAPI 提供強大的依賴注入系統和例外處理機制。
from fastapi import Depends, HTTPException
async def verify_token(x_token: str = Header(...)):
if x_token != "secret":
raise HTTPException(status_code=401)
@app.get("/items/", dependencies=[Depends(verify_token)])
async def read_items():
return [{"item": "Foo"}]