from fastapi import FastAPI, Query, Path
app = FastAPI()
# 使用 Query 参数
@app.get("/items/")
async def read_item(
q: str = Query(..., title="Query参数", description="这是一个查询参数", min_length=3, max_length=50)
):
return {"q": q}
# 使用 Path 参数
@app.get("/items/{item_id}")
async def read_item_path(
item_id: int = Path(..., title="路径参数", description="这是一个路径参数", ge=1, le=100)
):
return {"item_id": item_id}
在上面的例子中,我们定义了两个路由,一个使用Query参数,另一个使用Path参数。在每个参数中,我们都提供了一些额外的信息:
- title: 参数的标题。
- description: 参数的描述。
- min_length 和 max_length: 限制字符串参数的最小和最大长度。
- ge 和 le: 限制整数参数的最小和最大值。
你可以使用[httpie](https://httpie.io/)或其他工具来测试这个API。以下是一些示例:
# 测试 Query 参数
http "http://127.0.0.1:8000/items/?q=test"
# 测试 Path 参数
http "http://127.0.0.1:8000/items/42"
在这个例子中,我们通过HTTP请求发送了一个查询参数和一个路径参数。FastAPI将根据提供的额外信息来验证和解析这些参数。
转载请注明出处:http://www.zyzy.cn/article/detail/7369/FastAPI