山东省建设科技协会网站,南昌网站建设工作,贵德县建设局网站,营销广告文案FastAPI 路径参数详解#xff1a;动态路径与数据校验的灵活实现
本文全面介绍了在 FastAPI 中使用路径参数的技巧和实现方式。路径参数允许 API 动态响应不同路径中的请求信息#xff0c;结合 URL#xff08;Uniform Resource Locator#xff09;和 URI#xff08;Unifor…FastAPI 路径参数详解动态路径与数据校验的灵活实现
本文全面介绍了在 FastAPI 中使用路径参数的技巧和实现方式。路径参数允许 API 动态响应不同路径中的请求信息结合 URLUniform Resource Locator和 URIUniform Resource Identifier进行资源定位和标识。URL 是指资源的完整访问路径用于确定资源的具体位置而 URI 则是更广义的概念包含 URL在 URL 的基础上提供对特定资源的唯一标识。文中通过类型声明实现了路径参数的数据转换与校验确保路径中的参数符合预期格式。本文还展示了路径参数类型、数据校验、路径操作顺序和 Enum 类型的使用提供了定义固定值路径参数的示例。此外文章解释了如何声明包含文件路径的路径参数并提供了具体的代码示例是学习 FastAPI 路径参数与资源标识的实用指南。 文章目录 FastAPI 路径参数详解动态路径与数据校验的灵活实现一 路径参数1 示例2 路径参数类型3 数据转换4 数据校验 二 路径操作的顺序三 使用 Enum 类型预定义路径参数的值1 比较枚举元素2 获取枚举值3 返回枚举元素 四 包含文件路径的路径参数五 完整代码示例六 源码地址 一 路径参数
在 FastAPI 中路径参数通过在路径字符串中包含变量来定义。路径参数用于接收请求 URL 中的动态部分使得 API 可以根据不同的路径值响应不同的内容。具体来说路径参数在路径中通过花括号来标识并在相应的函数参数中进行定义和使用。例如在路径 /items/{item_id} 中{item_id} 就是路径参数。
1 示例
以下是一个简单的示例代码
from fastapi import FastAPIapp FastAPI()app.get(/items/{item_id})
async def read_item(item_id):return {item_id: item_id}在这个例子中路径参数 item_id 的值会被传递给路径操作函数的参数 item_id。可以运行代码文件 chapter02.py 来启动应用
$ uvicorn chapter02:app --reload访问自动生成的 API 文档 Swagger UIhttp://127.0.0.1:8000/docs。通过访问 http://127.0.0.1:8000/items/foo可以获得如下返回
{item_id: foo}2 路径参数类型
在以下代码中item_id 的类型声明为 int
from fastapi import FastAPIapp FastAPI()app.get(/items02/{item_id})
async def read_item(item_id: int):return {item_id: item_id}3 数据转换
FastAPI 可以通过类型声明自动解析请求中的数据并进行数据转换。例如路径 /items/3 中的字符串 3 会被自动转换为整数 3。
4 数据校验
FastAPI 使用 Python 类型声明来实现数据校验。如果请求中的值与声明的类型不匹配将返回错误信息。例如对于 async def read_item(item_id: int)当请求路径为 /items/foo 时返回的错误信息如下
{detail: [{type: int_parsing,loc: [path,item_id],msg: Input should be a valid integer, unable to parse string as an integer,input: foo}]
}在 FastAPI 中数据校验由 Pydantic 实现。
二 路径操作的顺序
路径操作按定义顺序依次运行。如果一个 URI 既与特定路径匹配又与包含路径参数的路径匹配应将特定路径的操作放在前面包含路径参数的路径写在后面。例如
from fastapi import FastAPIapp FastAPI()app.get(/users/me)
async def read_user_me():return {user_id: the current user}app.get(/users/{user_id})
async def read_user(user_id: str):return {user_id: user_id}注意/users/me 必须在 /users/{user_id} 之前声明否则 /users/{user_id} 将匹配 /users/me并将 me 作为 user_id 的值。
三 使用 Enum 类型预定义路径参数的值
可以使用 Python 的 Enum 类型来预定义路径参数的值。
from enum import Enum
from fastapi import FastAPIclass ModelName(str, Enum):alexnet alexnetresnet resnetlenet lenetapp FastAPI()app.get(/models/{model_name})
async def get_model(model_name: ModelName):if model_name is 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}使用 Enum 类ModelName可以为路径参数 model_name 设置类型注解。
1 比较枚举元素
if model_name is ModelName.alexnet:2 获取枚举值
model_name.value或
ModelName.lenet.value3 返回枚举元素
return {model_name: model_name, message: Have some residuals}请求访问 http://127.0.0.1:8000/models/resnet 时客户端将收到如下 JSON 响应
{model_name: resnet,message: Have some residuals
}四 包含文件路径的路径参数
可以直接使用 Starlette 的选项声明包含路径的路径参数
/files/{file_path:path}在这个示例中参数名为 file_path结尾部分的 :path 表示该参数应匹配整个路径。例如包含 /home/your/myfile.txt 的路径参数必须以斜杠/开头。在这个例子中URI 为 /files//home/your/myfile.txtfiles 和 home 之间需要使用双斜杠//。
注OpenAPI 不支持声明包含路径的路径参数因此访问 /files/{file_path} 时可能会报错 {detail: Not Found}。
五 完整代码示例
from fastapi import FastAPI
from enum import Enumapp FastAPI()app.get(/items/{item_id})
async def read_item(item_id):return {item_id: item_id}app.get(/items02/{item_id})
async def read_item(item_id: int):return {item_id: item_id}app.get(/users/me)
async def read_user_me():return {user_id: the current user}app.get(/users/{user_id})
async def read_user(user_id: str):return {user_id: user_id}class ModelName(str, Enum):alexnet alexnetresnet resnetlenet lenetapp.get(/models/{model_name})
async def get_model(model_name: ModelName):if model_name is 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}app.get(/files/{file_path:path})
async def read_file(file_path: str):return {file_path: file_path}
六 源码地址
详情见GitHub FastApiProj
引用 FastAPI 文档