什么是路徑
- 假設一個 url 是: http://127.0.0.1:8080/items/abcd
- 那么路徑 path 就是 /items/abcd
路徑參數
就是將路徑上的某一部分變成參數,可通過請求傳遞,然后 FastAPI 解析
最簡單的栗子
import uvicorn from fastapi import FastAPI app = FastAPI() # 路徑參數 item_id @app.get("/items/{item_id}") async def read_item(item_id): return {"item_id": item_id} if __name__ == '__main__': uvicorn.run(app="2_get:app", host="127.0.0.1", port=8080, reload=True, debug=True)
postman 請求結果
限定類型的路徑參數
# 指定類型的路徑參數 @app.get("/items/{item_id}/article/{num}") async def path_test(item_id: str, num: int): return {"item_id": item_id, "num": num}
多個路徑參數,且有指定類型
正確傳參的請求結果
123 傳進來的時候是字符串,但 FastAPI 會自動解析轉換成 int,如果轉換失敗就會報錯
num 不傳 int 的請求結果
友好的錯誤提示類型不對
Swagger 接口文檔的顯示效果
路徑函數順序問題
@app.get("/users/me") async def read_user_me(): return {"user_id": "the current user"} @app.get("/users/{user_id}") async def read_user(user_id: str): return {"user_id": user_id}
/users/{user_id} 路徑是包含 /users/me 的
當想匹配到固定路徑時,需要將固定路徑函數放在路徑參數函數前面
postman 請求結果
將兩個函數順序換過來
@app.get("/users/{user_id}") async def read_user(user_id: str): return {"user_id": user_id} # 順序問題 @app.get("/users/me") async def read_user_me(): return {"user_id": "the current user"}
這樣就無法匹配到固定路徑 /users/me 的函數了
路徑轉換器
前言
- 當你有一個路徑是 /files/{file_path} ,但是不確定 file_path 到底會取什么值,並不是固定的長度,可能是 /files/home/johndoe/myfile.txt 也可能是 /files/test/myfile.txt ,那怎么辦呢?
- 路徑轉換器出來啦!
實際栗子
# 路徑轉換器 @app.get("/files/{file_path:path}") async def read_file(file_path: str): return {"file_path": file_path}
postman 請求結果
枚舉類型的路徑參數
# 導入枚舉類 from enum import Enum # 自定義枚舉類 class ModelName(Enum): polo = "polo" yy = "yy" test = "test" @app.get("/models/{model_name}") # 類型限定為枚舉類 async def get_model(model_name: ModelName): # 取枚舉值方式一 if model_name == ModelName.polo: return {"model_name": model_name, "message": "oh!!polo!!"} # 取枚舉值方式二 if model_name.value == "yy": return {"model_name": model_name, "message": "god!!yy"} return {"model_name": model_name, "message": "巴拉巴拉"}
參數傳枚舉值的請求結果
參數傳非枚舉值的請求結果
錯誤提示傳的參數值並不是枚舉類中的值
重點:路徑參數可以不傳嗎?
先說答案,不行!路徑參數是必傳參數
實際栗子
# 路徑參數 item_id @app.get("/items/{item_id}") async def read_item(item_id): return {"item_id": item_id}
假設不傳 item_id
總結
路徑參數是請求路徑的一部分,如果不傳,請求的是另一個路徑,如果不存在就會 404