FastAPI 是一款基于 Python 的快速 Web 框架,用于構(gòu)建 API。它基于 Python 的類型提示,讓代碼更具可讀性和可維護性,且性能卓越。?
安裝 FastAPI?
安裝 FastAPI 很簡單,通過 pip 即可:?
?
TypeScript
取消自動換行復(fù)制
pip install fastapi uvicorn?
?
其中,uvicorn是一個 ASGI 服務(wù)器,用于運行 FastAPI 應(yīng)用。?
創(chuàng)建基礎(chǔ)應(yīng)用?
創(chuàng)建一個基本的 FastAPI 應(yīng)用只需幾行代碼:?
?
TypeScript
取消自動換行復(fù)制
from fastapi import FastAPI?
?
app = FastAPI()?
?
@app.get("/")?
def read_root():?
return {"Hello": "World"}?
?
上述代碼中,先導(dǎo)入FastAPI類,創(chuàng)建app實例。使用@app.get("/")裝飾器定義一個處理根路徑/的 GET 請求的函數(shù)read_root,函數(shù)返回一個 JSON 格式數(shù)據(jù){"Hello": "World"}。?
添加路由?
定義多個 API 端點,如:?
?
TypeScript
取消自動換行復(fù)制
@app.get("/items/{item_id}")?
def read_item(item_id: int):?
return {"item_id": item_id}?
?
這里@app.get("/items/{item_id}")定義了一個接收路徑參數(shù)item_id的 GET 請求路由,item_id類型為int,函數(shù)返回包含item_id的 JSON 數(shù)據(jù)。?
處理請求參數(shù)?
FastAPI 能方便地處理查詢參數(shù):?
?
TypeScript
取消自動換行復(fù)制
@app.get("/users/")?
def read_users(q: str = None):?
if q:?
return {"query": q}?
return {"message": "No query provided"}?
?
在這個例子中,q是一個可選的查詢參數(shù),若有值則返回包含q的 JSON 數(shù)據(jù),否則返回提示消息。?
運行應(yīng)用?
在終端中運行:?
?
TypeScript
取消自動換行復(fù)制
uvicorn main:app --reload?
?
這里main是 Python 文件名,app是 FastAPI 應(yīng)用實例名,--reload參數(shù)可在代碼修改時自動重啟服務(wù)器,方便開發(fā)調(diào)試。?
FastAPI 憑借簡潔的語法和強大的功能,讓開發(fā)者能高效構(gòu)建健壯的 API,無論是小型項目還是大型企業(yè)級應(yīng)用都十分適用。





暫無評論,快來評論吧!