FastAPI 路径参数和数值校验
除了可以为Query
查询参数声明校验和元数据,还可以为Path
路径参数声明相同类型的校验和元数据。
声明元数据
可以声明与Query相同的所有参数。
例如:为路径参数item_id声明title元数据的值时,可以输入:
from typing import Optional
from fastapi import FastAPI. Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int = Path(..., title="The ID of the item to get"), q: Optional[str] = Query(None, alias="item-query")):
results = {"item_id": item_id}
if q:
result.update({"q": q})
return results
因为路径参数必须是路径的一部分,所以路径参数总是必选的,因此,声明路径参数时要使用...,把它标记为必选参数。不过,就算使用None声明路径参数,或设置其他默认值也不会有任何影响,路径参数依然是必选参数。
按需排序参数
假设要把查询参数q
声明为必选的str
类型。而且,因为不用为该参数声明任何其他内容,因此无需使用Query
。但仍然使用Path
声明路径参数item_id
,如果把有默认值的参数置于无默认值的参数前,python会报错,但可以重新排序,把无默认值的查询参数q
放到最前面。
from fastapi import FastAPI, Path
app = FastAPI()
@app.get("/items/{item_id}")
async def read_items(q: str, item_id: int = Path(..., titile = "The ID of the item to get")):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
按需排序参数的技巧
如果不想使用Query
声明没有默认值的查询参数q
,但同时还要使用Path
声明路径参数item_id
,并使用不同的排序方式,可以使用python的特殊语法。把*
作为函数的第一个参数,python不对*
执行任何操作,但会把*
之后的参数都当做关键字参数。
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
数值校验:大于等于
使用Query
和Path
时,既可以声明字符串约束,也可以声明数值约束。此处,添加ge=1
后,item_id
就必须就必须是大于等于1
的整数。
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", ge=1), q: str):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
数值校验:大于、小于等于
gt
:大于le
:小于等于
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", gt=0, le=1000), q: str):
results = {"item_id": item_id}
if q:
results.update({"q": q})
return results
数值校验:浮点数、大于和小于
数值校验同样适用于float
值,此处,重要的是声明gt
,而不仅是ge
,例如,值必须大于0
,即使该值小于1
,因此,0.5
是有效的,但0.0
或0
是无效的。
from fastapi import FastAPI, Path, Query
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(*,
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
声明数值校验:
gt
:大于ge
:大于等于lt
:小于le
:小于等于
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!