今天來說說 Python 框架三本柱的第三柱 FastAPI。
FastAPI 在近年來成為熱門框架,不只是因為它夠「快」,還因為它在設計理念上很符合現代 Web 開發需求。
從 API 可以看的出來主要用來開發 API (Application Programming Interface),以下介紹該框架的優勢:
Swagger UI
。poetry init -n
poetry shell
poetry add fastapi uvicorn
啟動
uvicorn main:app --reload
這邊舉個簡單例子:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def demo():
return {"message": "hello world."}
@app.get("/items/{item_id}")
def item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
這時候啟動伺服器後可以使用Swagger UI
查看 API 文件,也可透過該文件進行測試,相當方便。
http://127.0.0.1:8000/docs
上述有提到 FastAPI 提供了請求驗證,可以透過 Pydantic 進行參數的驗證:
從範例來看當使用者將price
欄位內容傳入字串 Str
時,FastAPI 會自動回傳錯誤訊息。
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def item(item: Item):
return item
那麼今天就介紹到這,明天見ㄅㄅ!