文件名稱 | 版本號 | 作者 | 版本 | |
---|---|---|---|---|
寫Python API好簡單,非Gen | v1.0.0 | 學生宮布 | 8416837 | Python 3.8 FastAPI (0.1.0) |
FastAPI
Demo
- 這裏假設你已經會使用一款IDE(集成開發環境)或命令行
依賴
- 安裝依賴
用的工具可能是pip
|pip3
執行pip3 --help
試一下。
如果以下安裝太慢,請使用國內鏡像。
pip3 install fastapi
# ASGI 服務:uvicorn:
pip3 install uvicorn
代碼
- 主類 main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/{name}")
def read_root(name):
return {"Hello": "World" + name}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
啓動
命令行啓動項目
uvicorn main:app --reload
【注意】IDE執行上述命令可能因配置問題而閃退
啓動成功:
調用
- 接口1
localhost:8000/_name
- 接口2
localhost:8000/items/3001?q=狗
文檔
- FastAPI自帶文檔,地址是
http://localhost:8000/docs
- 同時自帶redoc文檔,訪問地址是
http://localhost:8000/redoc
炫技
參數驗證
Json參數的接口
- 代碼比上述代碼複雜一點點
- 服務端:
from pydantic import BaseModel
from fastapi import FastAPI
app = FastAPI()
class Dog(BaseModel):
nick_name: str
tooth: int
sex: int
age_month: float
@app.post("/dog")
def read_item(dog: Dog):
print(dog)
return dog
- 客戶端:
HTTPClient傳json參數,以期獲得響應參數
import requests
url = "http://localhost:8000/dog"
params = {"nick_name":"QWo","sex":1,"tooth":34, "age_month": 13.5}
res = requests.post(url,json=params)
res.json()
執行請求,響應沒問題:
測試功能
- 框架底層做了封裝,使用Python HTTPClient隨手測試一下
import requests
url = "http://localhost:8000/dog"
params = {"nick_name":"QWo","sex":1,"tooth":"99"}
res = requests.post(url,json=params)
res.json()
- 故意傳錯參數試試:
↑自動將字符串強轉成了數字。 - 改成非數字,報錯了:
- 漏傳參數,友好提示:
↑age_month參數漏傳了。 - 將參數改爲非必傳(not required):
加上= None
- 謝謝!更多炫技待續。。。