
http://127.0.0.1:8080/items/abcd
/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)
# 指定类型的路径参数
@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,如果转换失败就会报错

友好的错误提示类型不对

@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 的
当想匹配到固定路径时,需要将固定路径函数放在路径参数函数前面

@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}
# 路径转换器
@app.get("/files/{file_path:path}")
async def read_file(file_path: str):
return {"file_path": file_path}

# 导入枚举类
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}
路径参数是请求路径的一部分,如果不传,请求的是另一个路径,如果不存在就会 404