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