FastAPI 路径参数及校验
Path 路径参数约束
注意: 对于必需参数,我们没有顺序要求,有默认值的参数必须放在没有默认值的后面
from fastapi import FastAPI
app = FastAPI()
# 未约束路径参数内容
@app.get('/a/{name}')
async def name1(name):
return {'name': name}
# 约束路径参数类型
@app.get('/b/{age}')
async def name(age:int):
return {'age': age}
# 启动: uvicorn main:app --reload
# 未约束
curl 127.0.0.1:8000/a/asdf
{"name":"asdf"}
# 约束错误返回
curl 127.0.0.1:8000/b/asdf
{"detail":[{"loc":["path","age"],"msg":"value is not a valid integer","type":"type_error.integer"}]}
# 约束 int 类型
curl 127.0.0.1:8000/b/1
{"age":1}
路径参数枚举
class SexyEnum(str, Enum):
''' key = value '''
boy = 1
girl = 2
@app.get("/sexy/{value}")
async def sexy(value: SexyEnum):
''' 通过判断 value 值判断'''
if value == SexyEnum.boy:
return {'name': 'boy'}
if value == SexyEnum.girl:
return {'name': 'girl'}
curl 127.0.0.1:8000/sexy/1
{"name":"boy"}
curl 127.0.0.1:8000/sexy/2
{"name":"girl"}
curl 127.0.0.1:8000/sexy/3
{"detail":[{"loc":["path","value"],"msg":"value is not a valid enumeration member; permitted: '1', '2'","type":"type_error.enum","ctx":{"enum_values":["1","2"]}}]}
路径参数校验
例如传ID, id 必须是 int 类型,并且不能为空,自定义标题为 user id
from typing import Optional, List
from fastapi import FastAPI,Query,Path
app = FastAPI()
@app.get('/items/{id}')
async def items(id: int = Path(..., title='user id')):
return {'id': id}
curl 127.0.0.1:8000/items/1
{"id":1}
* 号作用
*
星号之后所有参数都应称为关键字参数, 必须传入
(键-值对),也称为kwargs 。 即使它们没有默认值。
路径参数和请求参数结合
from typing import Optional
from fastapi import FastAPI,Query,Path
app = FastAPI()
@app.get('/items/{id}')
async def items(*,
id: int = Path(..., title='id'),
q: str, # 关键字参数,必须传入
):
return {'id': id, 'q': q}
Last updated