1.参数接收
1.1 路径参数(不推荐)
1.代码清单
在app/router
下,新增demo_router.py
文件,内容如下:
from fastapi import APIRouter
router = APIRouter(
prefix="/demo",
tags=["演示接口"]
)
@router.get("/path/{order_id}")
async def pathParamReceive(order_id: int):
"""
路径参数接收演示
"""
return {
"接受结果": order_id,
}
@注意:当我们定义参数类型时,FastAPI 接受参数时,会自动进行"解析",如果类型不一致,则会报错。
2.请求验证
# 正常传参
➜ curl http://127.0.0.1:8000/demo/path/12222
{"接受结果":12222}
# 当传参类型不匹配时,接口定义是:int
➜ curl http://127.0.0.1:8000/demo/path/hello
{"detail":[{"loc":["path","order_id"],"msg":"value is not a valid integer","type":"type_error.integer"}]}
# 当什么都不传时
➜ curl http://127.0.0.1:8000/demo/path/
{"detail":"Not Found"}
3.顺序大坑
假如我们定义两个接口,带路径参数的:/path/{order_id}
和不带路径参数的:/path/test
,可能会因为顺序问题,导致我们无法正常访问/path/test
,例如路由注册时代码如下:
...
@router.get("/path/{order_id}")
async def pathParamReceive(order_id: int):
"""
路径参数接收-演示-带路径参数
"""
return {
"接受结果": order_id,
}
@router.get("/path/test")
async def pathParamReceive2():
"""
路径参数接收-演示-不带路径参数
"""
return {
"msg": "hello",
}
然后进行访问:
# 带路径参数的可以正常访问
➜ curl http://127.0.0.1:8000/demo/path/99999
{"接受结果":99999}
# 不带路径参数的可以正常访问
➜ curl http://127.0.0.1:8000/demo/path/test
{"detail":[{"loc":["path","order_id"],"msg":"value is not a valid integer","type":"type_error.integer"}]}
通过替换两个函数位置,就可以正常访问了, 感觉比较奇葩,不推荐使用,只做了解即可。更多使用方法可见官方文档: fastapi.tiangolo.com/zh/tutorial…
1.2 查询参数
1.代码清单
在app/router
下