FastAPI 允许你为参数声明额外的信息和校验
路径参数校验
对于路径参数,我们通常会对路径参数的类型进行校验,判断其是否符合要求。通常我们会这么做:
@app.get("/items/{item_id}")
async def item_details(item_id: uuid.UUID|int):
return {
"item_id": item_id}
用于判断传递的参数是否为uuid.UUID
类型或者int
类型。当传递的item_id不是uuid.UUID
类型或者int
类型,将会引发422错误。错误信息如下:
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid uuid",
"type": "type_error.uuid"
},
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
这只是对参数的类型做一些校验,如果我们需要做一些复杂的校验,例如对参数的大小,长度做判断时,我们可以使用到Path
类型。使用如下:
from fastapi import Path
@app.get("/items/{item_id}")
async def item_details(item_id: int = Path(gt=0, lt=100)):
return {
"item_id": item_id}
表示只接收大于0,且小于100的item_id参数。若不符合条件,同样也会引发422错误。Path
除了可以对参数做一些校验操作之外,它还可以在Swagger UI中,对该接口参数做一些说明,如下:
from fastapi import Path
@app.get("/items/{item_id}")
async def item_details(item_id: int = Path(title='标题', description=