FastAPI 使用python 字符串格式化语法声明路径参数(变量)。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id):
return {"item_id" : item_id}
上面代码中把路径参数 item_id的值传递给路径函数的参数 item_id。
运行代码,访问 http://127.0.0.1:8000/items/foo,返回的响应结果如下:
{"item_id" : "foo"}
声明路径参数的类型
使用python标准类型注释,声明路径操作函数中路径参数的类型。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
本例中将变量 item_id 的类型声明为整型 int。
运行代码,访问 http://127.0.0.1:8000/items/3,返回的响应结果如下:
{"item_id": 3}
FastAPI 通过类型声明自动解析请求中的数据,使用python类型声明实现了数据校验。
如果访问URL http://127.0.0.1:8000/item/foo传入的 item_id参数值不是 int类型时,则响应报错信息如下:
{
"detail": [
{
"loc": [
"path",
"item_id"
],
"msg": "value is not a valid integer",
"type": "type_error.integer"
}
]
}
预设路径参数
路径操作使用python的 Enum类型接收预设的路径参数。
导入 Enum并创建继承自 str和 Enum的子类,通过从 str继承,API文档就能把值的类型定义为字符串,然后创建包含固定值的类属性。
from enum import Enum
from fastapi import FastAPI
class ModelName(str, Enum):
alexnet = "alexnet"
resnet = "resnet"
lenet = "lenet"
app = FastAPI()
@app.get("/models/{model_name}")
async def get_model(model_name: ModelName):
if model_name == ModelName.alexnet:
return {"model_name": model_name, "message": "Deep Learning FTW !"}
if model_name.value == "lenet":
return {"model_name": model_name, "message": "LeCNN all the images"}
return {"model_name": model_name, "message": "Have some residuals"}
访问URL http://127.0.0.1:8000/models/alexnet响应结果如下:
{
"model_name":"alexnet",
"message":"Deep Learning FTW !"
}
访问URL http://127.0.0.1:8000/models/lenet响应结果如下:
{
"model_name":"lenet",
"message":"LeCNN all the images"
}
访问URL http:127.0.0.1:8000/models/resnet响应结果如下:
{
"model_name":"resnet",
"message":"Have some residuals"
}
包含路径的路径参数
假设路径操作的路径为 /file/{file_path},但是需要 file_path中包含路径,比如, home/johndoe/myfile.txt,此时的文件URL是这样的: /files/home/johndoe/myfile.txt。
直接使用Starlette的选项声明包含路径的路径参数:/files/{file_path: path}
from fastapi import FastAPI
app = FastAPI()
@app.get("/files/{file_path: path}")
async def read_file(file_path: str):
return {"file_path": file_path}
注意:
包含 /home/johndoe/myfile.txt的路径参数要以斜杠开头。
本例中的URL是 /files/home/johndoe/myfile.txt files 和 home 之间要使用双斜杠 //
浙公网安备 33010602011771号