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
之间要使用双斜杠 //
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现