
FastAPI 是一個現(xiàn)代、高性能的 Python Web 框架專為構建 API 而生。它基于 Python 的類型提示能夠自動進行數(shù)據(jù)校驗并生成 API 文檔是當前 Python 生態(tài)中增長最快的 Web 框架之一。FastAPI 的核心特性FastAPI 之所以備受青睞主要得益于它這些“自帶光環(huán)”的特性極高的性能基于 Starlette異步框架和 Pydantic數(shù)據(jù)校驗庫構建性能可媲美 Node.js 和 Go在 Python Web 框架中處于頂尖水平。自動生成 API 文檔無需手動編寫代碼即文檔。它會自動為你生成交互式 Swagger UI (/docs) 和 ReDoc (/redoc) 文檔極大方便了調(diào)試和前后端協(xié)作。強大的數(shù)據(jù)校驗利用 Pydantic 和 Python 類型提示能自動校驗請求體、查詢參數(shù)等確保數(shù)據(jù)準確并在校驗失敗時自動返回清晰的錯誤信息。原生異步支持完美支持async/await語法能高效處理高并發(fā) I/O 場景非常適合構建微服務和實時 Web 應用。靈活的依賴注入系統(tǒng)通過Depends機制可以輕松管理數(shù)據(jù)庫會話、權限驗證、配置等依賴讓代碼更解耦、更易于測試和復用。使用1. 安裝與環(huán)境準備建議創(chuàng)建一個虛擬環(huán)境來隔離項目依賴。# 創(chuàng)建并激活虛擬環(huán)境 (以venv為例) python -m venv venv source venv/bin/activate # Linux/macOS # venv\Scripts\activate # Windows # 安裝 FastAPI 和 ASGI 服務器 Uvicorn pip install fastapi uvicorn[standard]2. 編寫第一個 API創(chuàng)建一個main.py文件from fastapi import FastAPI # 1. 創(chuàng)建 FastAPI 應用實例 app FastAPI() # 2. 定義路徑操作裝飾器 (根路徑 /) app.get(/) async def read_root(): # 返回 JSON 響應 return {message: Hello, FastAPI!} # 3. 定義另一個帶路徑參數(shù)的 API app.get(/items/{item_id}) async def read_item(item_id: int, q: str None): return {item_id: item_id, query: q}3. 啟動服務在終端中運行以下命令uvicorn main:app --reloadmain指main.py文件。app指文件中創(chuàng)建的FastAPI實例。--reload開啟熱重載代碼修改后服務器會自動重啟方便開發(fā)。4. 查看效果服務啟動后可以訪問以下地址API 端點http://127.0.0.1:8000/或http://127.0.0.1:8000/items/5Swagger UI 文檔http://127.0.0.1:8000/docsReDoc 文檔http://127.0.0.1:8000/redoc路由與參數(shù)定義路由使用裝飾器app.get()、app.post()、app.put()、app.delete()等來定義對應 HTTP 方法的路由。from fastapi import FastAPI app FastAPI() app.get(/users/) async def get_users(): return [{username: alice}, {username: bob}] app.post(/users/) async def create_user(): # 創(chuàng)建用戶的邏輯 return {message: User created}參數(shù)處理FastAPI 能自動識別三種主要參數(shù)類型。1. 路徑參數(shù)從 URL 路徑中獲取參數(shù)并支持類型聲明和校驗。from fastapi import FastAPI, Path app FastAPI() app.get(/books/{book_id}) async def get_book( # 路徑參數(shù) book_id, 類型為 int, 校驗其值大于 0 且小于 101 book_id: int Path(..., title書籍ID, ge1, le100) ): return {book_id: book_id}2. 查詢參數(shù)URL 中問號后的鍵值對如/items?skip0limit10。from fastapi import FastAPI, Query app FastAPI() app.get(/items/) async def list_items( # 查詢參數(shù) skip 和 limit帶默認值和描述 skip: int Query(0, description跳過的記錄數(shù)), limit: int Query(10, description返回的記錄數(shù)) ): return {skip: skip, limit: limit}3. 請求體參數(shù)用于POST、PUT等請求將 JSON 數(shù)據(jù)映射到 Pydantic 模型中。from fastapi import FastAPI from pydantic import BaseModel, Field app FastAPI() # 1. 定義請求體的數(shù)據(jù)結構 class UserCreate(BaseModel): username: str Field(..., min_length3, max_length20, description用戶名) password: str Field(..., min_length6, description密碼) app.post(/register/) async def register_user(user: UserCreate): # FastAPI 會自動將 JSON 請求體解析為 UserCreate 實例 return {message: fUser {user.username} registered}核心功能功能說明示例場景依賴注入通過Depends注入數(shù)據(jù)庫會話、配置、認證等依賴實現(xiàn)解耦和復用。db: Session Depends(get_db)響應模型使用response_model參數(shù)來過濾和格式化輸出數(shù)據(jù)確保 API 返回結構一致。app.get(/user, response_modelUserOut)中間件處理請求和響應的全局邏輯如日志記錄、CORS 配置。全局異常捕獲、跨域設置。后臺任務使用BackgroundTasks將發(fā)送郵件、處理圖片等耗時操作放到后臺異步執(zhí)行不阻塞響應。用戶注冊后發(fā)送歡迎郵件。文件上傳通過UploadFile類型輕松處理文件上傳。用戶頭像上傳。WebSocket支持 WebSocket 協(xié)議用于構建聊天、實時通知等應用。實時聊天室。