FastAPI 基礎:安裝、項目結構與第一個 API
FastAPI 是一個高性能、基于類型提示的現代 Web 框架,具備自動生成 API 文檔、數據驗證和異步支持等特性。
在本篇文章中,你將學到:
- 如何安裝 FastAPI 并運行你的第一個 API
- 標準的 FastAPI 項目結構
- 如何拆分 API 代碼,提高可維護性
1. 安裝 FastAPI
FastAPI 依賴 Python 3.7+,你可以使用 pip 進行安裝:
pip install fastapi
FastAPI 需要一個 ASGI 服務器來運行,我們使用 Uvicorn:
pip install uvicorn
Uvicorn 是 FastAPI 推薦的高性能 ASGI 服務器,支持并發處理!
2. 規劃 FastAPI 項目結構
在開發實際項目時,建議使用模塊化結構,方便擴展與維護:
fastapi_project/
│── app/
│ ├── main.py # 入口文件
│ ├── routes/ # 路由管理
│ │ ├── users.py # 用戶相關 API
│ │ ├── items.py # 物品相關 API
│ ├── models/ # 數據庫模型
│ │ ├── user.py # 用戶模型
│ ├── schemas/ # Pydantic 數據驗證
│ ├── services/ # 業務邏輯層
│ ├── dependencies.py # 依賴注入
│ ├── config.py # 配置文件
│── requirements.txt # 依賴包
│── .env # 環境變量
為什么這樣組織代碼?
- routes/ ?? 負責 API 邏輯,按功能拆分
- models/ ?? 定義數據庫表結構(ORM)
- schemas/ ?? 負責請求和響應數據校驗(Pydantic)
- services/ ?? 處理核心業務邏輯
- dependencies.py ?? 依賴注入,提升代碼復用性
- config.py ?? 統一管理配置文件
推薦使用這種結構,避免 main.py 變得臃腫,提高代碼可維護性!
3. 編寫你的第一個 FastAPI API
(1) 創建 main.py
from fastapi import FastAPI
# 創建 FastAPI 應用實例
app = FastAPI()
# 定義 API 端點
@app.get("/")
def read_root():
return {"message": "?? Hello, FastAPI!"}
這個 API 處理 GET / 請求,并返回 JSON 響應:
{"message": "?? Hello, FastAPI!"}
(2) 運行 FastAPI 服務器
uvicorn app.main:app --reload
- app.main:app:表示 main.py 中的 app 實例
- --reload:啟用熱重載,代碼變更后無需手動重啟
啟動后,你可以訪問:
- 主頁 API: http://127.0.0.1:8000/
- Swagger API 文檔: http://127.0.0.1:8000/docs
- ReDoc API 文檔: http://127.0.0.1:8000/redoc
FastAPI 內置 API 文檔,省去手寫文檔的煩惱!
4. 組織 API 路由
為了更好地管理 API,我們將 API 拆分到 routes/ 目錄下。
(1) 創建 app/routes/items.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
(2) 在 main.py 中注冊路由
from fastapi import FastAPI
from app.routes import items
app = FastAPI()
# 注冊 API 路由
app.include_router(items.router, prefix="/api")
現在,你可以訪問 http://127.0.0.1:8000/api/items/1 進行測試!
5. FastAPI 的異步支持
FastAPI 原生支持 async/await,提高并發能力!例如,我們可以用 async def 讓 API 異步運行:
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get("/async")
async def async_example():
await asyncio.sleep(2) # 模擬異步任務
return {"message": "異步任務完成!"}
這樣,FastAPI 能同時處理多個請求,而不會阻塞主線程!
6. 解析請求參數(路徑參數 & 查詢參數)
(1) 路徑參數
@app.get("/users/{user_id}")
def read_user(user_id: int):
return {"user_id": user_id}
訪問 http://127.0.0.1:8000/users/10,返回:
{"user_id": 10}
(2) 查詢參數
@app.get("/search/")
def search(q: str, limit: int = 10):
return {"query": q, "limit": limit}
訪問 http://127.0.0.1:8000/search/?q=FastAPI&limit=5,返回:
{"query": "FastAPI", "limit": 5}
7. 結論:FastAPI 讓 API 開發更簡單!
FastAPI 優勢總結:
- 超快性能(比 Flask 快 3~5 倍)
- 自動生成 API 文檔(Swagger & ReDoc)
- 基于類型提示,代碼更清晰
- 原生支持異步 async/await