
如何快速實(shí)現(xiàn)REST API集成以優(yōu)化業(yè)務(wù)流程
FastAPI強(qiáng)制要求Python 3.6以上版本,因?yàn)樾枰玫筋愋吞崾具@個(gè)特性。裝之前記得看看自己Python版本夠不夠格。
這個(gè)功能太爽了!寫完代碼后,直接訪問?/docs
?路徑就能看到超漂亮的API文檔,都不用自己寫。代碼里加點(diǎn)注釋,文檔就自動生成了。
@app.get(“/items/{item_id}”)
def read_item(item_id: int, q: str = None):
“”“
獲取商品信息
- item_id: 商品ID
- q: 可選的查詢參數(shù)
”“”
return {“item_id”: item_id, “q”: q}
以前驗(yàn)證請求數(shù)據(jù)可費(fèi)勁了,現(xiàn)在用?Pydantic?模型,輕輕松松就搞定:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_sale: bool = False
@app.post(“/items/”)
def create_item(item: Item):
return item
要是數(shù)據(jù)格式不對,F(xiàn)astAPI自動返回錯(cuò)誤信息,都不用自己寫驗(yàn)證邏輯了,美滋滋。
FastAPI原生支持異步編程,處理并發(fā)請求特別在行:
@app.get(“/async_items/{item_id}”)
async def read_item_async(item_id: int):
# 假裝在查數(shù)據(jù)庫
await some_async_operation()
return {“item_id”: item_id}
用異步函數(shù)時(shí)記得加async
和await
關(guān)鍵字,不然代碼雖能跑,但壓根不是異步的。
想在多個(gè)接口間共享代碼?依賴注入幫你搞定:
def get_current_user(token: str):
if not token:
raise HTTPException(status_code=401)
return {“user”: “當(dāng)前用戶”}
@app.get(“/users/me”)
def read_user(user: dict = Depends(get_current_user)):
return user
寫項(xiàng)目一段時(shí)間就發(fā)現(xiàn)了,F(xiàn)astAPI是真的香。代碼寫起來快,運(yùn)行起來也快,還自帶各種方便的特性。新手友好,大佬也不嫌棄。
有人可能擔(dān)心性能問題。放心,F(xiàn)astAPI底層用的是?Starlette?和?Uvicorn?,性能相當(dāng)棒。測試顯示比很多其他Python框架都快好幾倍。
實(shí)在想不出還有啥理由不試試FastAPI。拿來寫API簡直完美,特別是搞些小項(xiàng)目,分分鐘就能搭起來。代碼寫得少,bug也少,開發(fā)效率杠杠的。
本文章轉(zhuǎn)載微信公眾號@iAmin啾