5.FastAPI显式声明参数
5.FastAPI显式声明参数FastAPI允许显式声明参数属于查询参数、路径参数或者请求体;同时还可以为参数声明默认值、额外的信息及校验;也允许显式声明可选参数;5.1可选参数可选参数的显式声明使用 typing. Optional来声明;代码如下:# coding: utf-8from typing import Optionalfrom fastapi import FastAPIapp
5.FastAPI显式声明参数
FastAPI允许显式声明参数属于查询参数、路径参数或者请求体;同时还可以为参数声明默认值、额外的信息及校验;也允许显式声明可选参数;
5.1可选参数
可选参数的显式声明使用 typing. Optional来声明;代码如下:
# coding: utf-8
from typing import Optional
from fastapi import FastAPI
app = FastAPI()
@app.get(path='/add/{vara}/{varb}')
async def add(vara: int, varb: int, x: Optional[int]=2, y: Optional[int] = 5):
return {'added': vara + varb, 'multiply': x * y}
执行请求:
curl http://127.0.0.1:8000/add/1/2
{"added":3,"multiply":10}
5.2查询参数
查询参数使用fastapi的Query来声明,声明时可以指定默认值,代码如下:
from typing import Optional
from fastapi import FastAPI
from fastapi import Query
app = FastAPI()
@app.get(path='/add/{vara}/{varb}')
async def add(vara: int, varb: int, x: Optional[int]=Query(2), y: Optional[int]=Query(5)):
return {'added': vara + varb, 'multiply': x * y}
上面的代码中使用 Query(2) 替换默认值 2,Query 的第一个参数也是用于定义默认值的,当使用Query声明必须参数时,可以将 ... 用作第一个参数值,代码如下:
from fastapi import FastAPI
from fastapi import Query
app = FastAPI()
@app.get(path='/add/{vara}/{varb}')
async def add(vara: int, varb: int, x: int=Query(...), y: int=Query(...)):
return {'added': vara + varb, 'multiply': x * y}
执行请求:
curl http://127.0.0.1:8000/add/1/2
{
"detail":[
{
"loc":["query","x"],
"msg":"field required",
"type":"value_error.missing"
},{
"loc":["query","y"],
"msg":"field required",
"type":"value_error.missing"
}
]
}
5.3路径参数
路径参数使用fastapi的Path来声明。由于路径参数是路径的一部分,所以路径参数一定是必需的。在声明路径参数时使用 ... 将其标记为必需参数。但实际上,即使使用 None 声明路径参数或设置一个其他默认值也不会有任何影响,仍然会是必需参数。代码如下:
from typing import Optional
from fastapi import FastAPI
from fastapi import Query
from fastapi import Path
app = FastAPI()
@app.get(path='/add/{vara}/{varb}')
async def add(vara: int=Path(...), varb: int=Path(...), x: Optional[int]=Query(2), y: Optional[int]=Query(5)):
return {'added': vara + varb, 'multiply': x * y}
执行请求:
curl http://127.0.0.1:8000/add/1/2
{"added":3,"multiply":10}
5.4请求体
路径参数使用fastapi的Body来声明。当在请求体中出现单一值而不是对象时,使用Body显式声明为请求体是有必要的。代码如下:
from fastapi import FastAPI
from pydantic import BaseModel
class Add(BaseModel):
a: int
b: int
class Mul(BaseModel):
x: int
y: int
app = FastAPI()
@app.post(path='/calc')
async def calc(add: Add, mul: Mul, index: int):
return {'added': add.a + add.b, 'multiply': mul.x * mul.y, index: index}
执行请求:
curl -H "Content-Type: application/json" -X POST -d "{\"add\": {\"a\":2, \"b\":3}, \"mul\": {\"x\":2, \"y\":3}, \"index\": 1018}" http://127.0.0.1:8000/calc
{
"detail":[
{
"loc":["query","index"],
"msg":"field required",
"type":"value_error.missing"
}
]
}
上面的代码中,index参数被解析为查询参数,所以在执行请求时会报错,将代码修改如下:
from fastapi import FastAPI
from fastapi import Body
from pydantic import BaseModel
class Add(BaseModel):
a: int
b: int
class Mul(BaseModel):
x: int
y: int
app = FastAPI()
@app.post(path='/calc')
async def calc(add: Add, mul: Mul, index: int=Body(...)):
return {'added': add.a + add.b, 'multiply': mul.x * mul.y, index: index}
执行请求:
curl -H "Content-Type: application/json" -X POST -d "{\"add\": {\"a\":2, \"b\":3}, \"mul\": {\"x\":2, \"y\":3}, \"index\": 1018}" http://127.0.0.1:8000/calc
{"added":5,"multiply":6,"1018":1018}
对于单个请求体来说,路由的请求体直接使用字段的key/value即可,但对于多个请求体,就向上面的例子,路由的请求体必须是嵌套式的,具体如下:
单个请求体,类似于:
{
"key1": "value1",
"key2": "value2",
......
}
多个请求体,类似于:
{
"key_1":{
"key1": "value1",
"key2": "value2",
......
},
"key_2":{
"key1": "value1",
"key2": "value2",
......
},
......
}
如果希望单个请求体也使用嵌套式,则在声明Body时,使用embed参数,代码如下:
from fastapi import FastAPI
from fastapi import Body
from pydantic import BaseModel
class Add(BaseModel):
a: int
b: int
app = FastAPI()
@app.post(path='/calc')
async def calc(add: Add=Body(..., embed=True)):
return {'added': add.a + add.b}
执行请求:
curl -H "Content-Type: application/json" -X POST -d "{\"a\":2, \"b\":3}" http://127.0.0.1:8000/calc
{
"detail":[
{
"loc":["body","add"],
"msg":"field required",
"type":"value_error.missing"
}
]
}
curl -H "Content-Type: application/json" -X POST -d "{\"add\": {\"a\":2, \"b\":3}}" http://127.0.0.1:8000/calc
{"added":5}
5.5请求体字段的显式声明
请求体中的字段可以使用Pydantic的Field在Pydantic模型定义时声明。 Field 是直接从pydantic导入的,而不像Query、Path和Body 都从 fastapi 导入的。
from typing import Optional
from fastapi import FastAPI
from fastapi import Body
from pydantic import BaseModel
from pydantic import Field
class Add(BaseModel):
a: Optional[int] = Field(1)
b: int = Field(...)
app = FastAPI()
@app.post(path='/calc')
async def calc(add: Add=Body(..., embed=True)):
return {'added': add.a + add.b}
执行请求:
curl -H "Content-Type: application/json" -X POST -d "{\"add\": {\"b\":5}}" http://127.0.0.1:8000/calc
{"added":6}
5.6参数的附加信息
参数的附加信息主要用于API文档。
元数据:
-
alias 别名,当参数名称是一个非 有效的 Python 变量名称时,可以使用alias标识别名
-
title 标题
-
description 描述
-
deprecated 启用,当参数在一段时间内保留,但希望文档中标识为已弃用时使用
代码示例:
from typing import Optional
from fastapi import FastAPI
from fastapi import Body
from pydantic import BaseModel
from pydantic import Field
class Add(BaseModel):
a: Optional[int] = Field(1, title='参数a', description='加数', alias='x')
b: int = Field(..., title='参数b', description='被加数', alias='y')
app = FastAPI()
@app.post(path='/calc')
async def calc(add: Add=Body(..., embed=True)):
return {'added': add.a + add.b}
API文档

执行请求:
curl -H "Content-Type: application/json" -X POST -d "{\"add\": {\"x\":2,\"y\":5}}" http://127.0.0.1:8000/calc
{"added":7}
5.7参数的校验
声明字符串校验:
-
min_length 最大长度
-
max_length 最小长度
-
regex 正则表达式
声明数值校验:
-
gt:大于(greater than)
-
ge:大于等于(greater than or equal)
-
lt:小于(less than)
-
le:小于等于(less than or equal)
代码示例:
from typing import Optional
from fastapi import FastAPI
from fastapi import Body
from fastapi import Query
from pydantic import BaseModel
from pydantic import Field
class Add(BaseModel):
a: Optional[int] = Field(1, title='参数a', description='加数', alias='x', gt=100)
b: int = Field(..., title='参数b', description='被加数', alias='y', ge=200)
app = FastAPI()
@app.post(path='/calc')
async def calc(add: Add=Body(..., embed=True), desc:str=Query(..., min_length=3, max_length=10)):
return {desc: add.a + add.b}
执行请求:
curl -H "Content-Type: application/json" -X POST -d "{\"add\": {\"x\":2,\"y\":5}}" http://127.0.0.1:8000/calc?desc=ad
{
"detail":[
{
"loc":["query","desc"],
"msg":"ensure this value has at least 3 characters",
"type":"value_error.any_str.min_length",
"ctx":{
"limit_value":3
}
},
{
"loc":["body","add","x"],
"msg":"ensure this value is greater than 100",
"type":"value_error.number.not_gt",
"ctx":{
"limit_value":100
}
},{
"loc":["body","add","y"],
"msg":"ensure this value is greater than or equal to 200",
"type":"value_error.number.not_ge",
"ctx":{
"limit_value":200
}
}
]
}
curl -H "Content-Type: application/json" -X POST -d "{\"add\": {\"x\":260,\"y\":500}}" http://127.0.0.1:8000/calc?desc=add
{"add":760}
更多推荐



所有评论(0)