FastAPI, 一個(gè)神奇的 Python 庫(kù)
FastAPI 是一個(gè)用于構(gòu)建 API 的現(xiàn)代、快速(高性能)的 web 框架,使用 Python 并基于標(biāo)準(zhǔn)的 Python類(lèi)型提示。

安裝
安裝 FastAPI 很簡(jiǎn)單,這里我們使用 pip 命令來(lái)安裝。
pip install fastapi另外我們還需要一個(gè) ASGI 服務(wù)器,生產(chǎn)環(huán)境可以使用 Uvicorn 或者 Hypercorn
pip install uvicorn[standard]資料:
- FastAPI 文檔:https://fastapi.tiangolo.com/zh/
- FastAPI 源碼:https://github.com/tiangolo/fastapi
簡(jiǎn)單示例
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}啟動(dòng)服務(wù):
uvicorn main:app --reload- --reload:開(kāi)發(fā)時(shí)自動(dòng)重載(生產(chǎn)環(huán)境移除)
- 訪(fǎng)問(wèn):http://localhost:8000
關(guān)鍵功能
(1) 路徑參數(shù)和查詢(xún)參數(shù)
- {user_id}:路徑參數(shù)(必須)
- limit 和 skip:查詢(xún)參數(shù)(可選,帶默認(rèn)值)
@app.get("/users/{user_id}")
async def read_user(user_id: int,
limit: int = 10,
skip: int = 0):
return {"user_id": user_id, "limit": limit, "skip": skip}(2) 請(qǐng)求體(POST/PUT)
使用 Pydantic 模型驗(yàn)證數(shù)據(jù):
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
@app.post("/items/")
async def create_item(item: Item):
return {"item": item.dict()}(3) 自動(dòng)文檔
- Swagger UI:http://localhost:8000/docs
- ReDoc:http://localhost:8000/redoc
(4) 異步支持
@app.get("/slow-endpoint")
async def slow_operation():
# 如數(shù)據(jù)庫(kù)查詢(xún)
await some_async_task()
return {"status": "done"}進(jìn)階功能
(1) 依賴(lài)注入
復(fù)用代碼邏輯(如認(rèn)證、數(shù)據(jù)庫(kù)連接)。
from fastapi import Depends
def common_params(q: str = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_params)):
return commons(2) 中間件
處理請(qǐng)求前/后的邏輯(如 CORS、日志)。
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
)(3) WebSocket 支持
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message: {data}")(4) 后臺(tái)任務(wù)
執(zhí)行無(wú)需即時(shí)響應(yīng)的操作(如發(fā)送郵件、短信)
from fastapi import BackgroundTasks
def log_task(message: str):
with open("log.txt", "a") as f:
f.write(message)
@app.post("/send-email")
async def send_email(background_tasks: BackgroundTasks):
background_tasks.add_task(log_task, "Email sent")
return {"status": "ok"}適用場(chǎng)景
- 構(gòu)建高性能 REST API
- 微服務(wù)后端
- 實(shí)時(shí)應(yīng)用(WebSocket)
- 結(jié)合sqlalchemy進(jìn)行 web 開(kāi)發(fā)




































