FastAPI 路径参数详解

FastAPI 路径参数详解

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API。它基于 Python 3.7+ 的类型提示(type hints)特性,提供了强大的数据验证和自动生成 API 文档的功能。在 FastAPI 中,路径参数(Path Parameters)是构建动态 URL 的核心功能之一。

什么是路径参数?

路径参数是 URL 中的一部分,用于捕获动态值。例如,在一个博客应用中,你可能希望通过 URL 来获取特定文章的详细信息。URL 可能看起来像这样:/articles/123,其中 123 是文章的 ID。在这个例子中,123 就是一个路径参数。

FastAPI 允许你通过定义路径操作函数(Path Operation Function)来捕获这些动态值,并将它们作为参数传递给函数。

基本用法

让我们从一个简单的例子开始。假设我们有一个 API,用于获取用户的详细信息。我们可以通过用户的 ID 来获取用户信息。

from fastapi import FastAPI

app = FastAPI()

@app.get("/users/{user_id}")
async def read_user(user_id: int):
    return {"user_id": user_id}

代码解析

  • 导入 FastAPI:首先,我们导入 FastAPI 类,它是构建 API 的核心类。
  • 创建 FastAPI 实例:我们创建了一个 FastAPI 实例,并将其赋值给 app 变量。
  • 定义路径操作函数:我们使用 @app.get("/users/{user_id}") 装饰器来定义一个 GET 请求的路径操作函数。{user_id} 是路径参数,FastAPI 会自动将其捕获并传递给函数。
  • 函数参数:read_user 函数的参数 user_id 被声明为 int 类型。FastAPI 会自动将 URL 中的 user_id 转换为整数类型,并进行数据验证。如果 user_id 不是整数,FastAPI 会返回一个 422 错误(Unprocessable Entity)。
  • 返回结果:函数返回一个包含 user_id 的字典。

测试 API

启动 FastAPI 应用后,你可以通过访问 /users/123 来测试这个 API。FastAPI 会自动将 123 转换为整数,并返回 {"user_id": 123}

路径参数的类型转换

FastAPI 支持多种类型的路径参数,包括 int、float、str、bool 等。你可以根据需要选择合适的类型。

示例:使用 str 类型的路径参数

@app.get("/items/{item_name}")
async def read_item(item_name: str):
    return {"item_name": item_name}

在这个例子中,item_name 是一个字符串类型的路径参数。你可以访问 /items/foo,FastAPI 会返回 {"item_name": "foo"}

示例:使用 float 类型的路径参数

@app.get("/prices/{price}")
async def read_price(price: float):
    return {"price": price}

在这个例子中,price 是一个浮点数类型的路径参数。你可以访问 /prices/19.99,FastAPI 会返回 {"price": 19.99}

路径参数的顺序

在 FastAPI 中,路径参数的顺序非常重要。如果你定义了多个路径参数,它们的顺序必须与 URL 中的顺序一致。

示例:多个路径参数

@app.get("/users/{user_id}/items/{item_id}")
async def read_user_item(user_id: int, item_id: int):
    return {"user_id": user_id, "item_id": item_id}

在这个例子中,我们定义了两个路径参数:user_id 和 item_id。你可以访问 /users/123/items/456,FastAPI 会返回 {"user_id": 123, "item_id": 456}

路径参数与查询参数的区别

路径参数是 URL 的一部分,而查询参数是 URL 中 ? 后面的部分。例如,在 /users/123?name=John 中,123 是路径参数,name=John 是查询参数。

示例:路径参数与查询参数结合使用

@app.get("/users/{user_id}")
async def read_user(user_id: int, name: str = None):
    return {"user_id": user_id, "name": name}

在这个例子中,user_id 是路径参数,name 是查询参数。你可以访问 /users/123?name=John,FastAPI 会返回 {"user_id": 123, "name": "John"}

路径参数的验证

FastAPI 提供了强大的数据验证功能。你可以通过类型提示来指定路径参数的类型,FastAPI 会自动进行验证。

示例:路径参数的验证

from fastapi import Path

@app.get("/users/{user_id}")
async def read_user(user_id: int = Path(..., gt=0)):
    return {"user_id": user_id}

在这个例子中,我们使用 Path 来对 user_id 进行额外的验证。gt=0 表示 user_id 必须大于 0。如果 user_id 不满足条件,FastAPI 会返回一个 422 错误。

总结

FastAPI 的路径参数功能非常强大且灵活。通过路径参数,你可以轻松构建动态 URL,并捕获 URL 中的动态值。FastAPI 还提供了丰富的类型支持和数据验证功能,帮助你构建健壮的 API。

在实际开发中,路径参数是构建 RESTful API 的重要组成部分。掌握路径参数的使用方法,可以帮助你更好地设计和实现 API。

posted @ 2025-01-23 10:42  darling331  阅读(151)  评论(0)    收藏  举报