Path Parameters and Numeric Validations
和用 Query 为查询参数声明更多的验证规则和元信息相同,可以用 Path 为路径参数声明同样的验证规则和元信息
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
Path 可声明的参数与 Query 完全相同,例如,在上述例子中,为 item_id 声明了元信息 title
注:因为路径参数总是必须的,因此可以用 ... 声明,实际上即使有默认值,也不会有效果,因为路径参数总是必须的
Order the parameters as you need
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(
q: str, item_id: int = Path(..., title="The ID of the item to get")
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
注意:
- python 总是要求位置参数在关键字参数前面,因此
q必须位于Path前 - 参数的顺序并不会影响 FastAPI,它关注的是参数的名字、类型和默认声明
Query,Path
Order the parameters as you need, tricks
from fastapi import FastAPI, Path
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
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
在 * 后面的参数即使没有默认值,也会被识别为关键字参数,因此可以如上例声明参数 666
Number validations: greater than or equal
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", ge=0, le=1000),
q: str,
size: float = Query(..., gt=0, lt=10.5)
):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
要点:
ge表示 greater equalgt表示 greater thanle表示 less equallt表示 less than
技术细节:
Query,Path等都是Param类的子类,它们共享相同的验证参数和元信息Query,Path等,其实只是函数,当他们被调用的时候,返回同名类的实例,例如当调用Query函数时,返回Query类的实例。这样做是为了避免直接使用类,这样编辑器就不会标记和他们类型有关的错误