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