你可以像在Query中定义的数据验证和metadata一样,在Path中使用。
eg:
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
item_id: int = Path(..., title="The ID of the item to get"),
q: str = Query(None, alias="item-query"),
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
按需排列参数
在python中是不允许将有默认值得参数放到没有默认值的参数之前的。
但是在fastapi中,是通过参数名来识别的,类型和默认值都不重要。
在fastapi中,当查询参数q不使用Query和路径参数使用Path,并且他们可以使用任意的顺序时,可以让函数的第一个参数为*
。。。
@app.get("/items/{item_id}")
async def read_items(
*, item_id: int = Path(…, title=“The ID of the item to get”), q: str
):
。。。
数字验证
。。。
@app.get("/items/{item_id}")
async def read_items(
*, item_id: int = Path(…, title=“The ID of the item to get”, ge=1), q: str
):
。。。
ge:大于等于
gt:大于
le:小于等于
lt:小于