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