通过实际示例来学习 FastAPI 的参数传递方式。我会逐步讲解不同的参数传递方式,并配上代码示例,你可以在本地运行并测试效果。
1. 路径参数 (Path Parameters)
路径参数是 URL 的一部分,通常用于标识特定的资源。例如:
python
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
📌 测试方式:
- 启动 FastAPI 服务器
uvicorn filename:app --reload
- 访问
http://127.0.0.1:8000/items/42
- 你会得到
{"item_id": 42}
🚀 关键点:
{item_id}
是路径参数,必须在 URL 中提供。- FastAPI 自动将
item_id
解析为int
,如果传入错误类型(如string
),会返回 422 错误。
2. 查询参数 (Query Parameters)
查询参数通常用于可选参数,它们出现在 ?key=value
形式的 URL 中。
python
@app.get("/search/")
async def search_items(q: str = "default", page: int = 1, size: int = 10):
return {"q": q, "page": page, "size": size}
📌 测试方式:
- 访问
http://127.0.0.1:8000/search/?q=FastAPI&page=2&size=5
- 你会得到
{"q": "FastAPI", "page": 2, "size": 5}
🚀 关键点:
q: str = "default"
设定了默认值,用户可以不提供参数。page: int = 1, size: int = 10
也有默认值,不传时会使用默认值。
3. 请求体参数 (Request Body Parameters)
适用于 POST
, PUT
等请求,数据格式通常为 JSON。
python
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str | None = None
price: float
quantity: int
@app.post("/items/")
async def create_item(item: Item):
return {"message": "Item created", "item": item}
📌 测试方式 : 使用 POST
请求,发送 JSON 数据:
json
{
"name": "Laptop",
"description": "A high-end gaming laptop",
"price": 1299.99,
"quantity": 5
}
你会得到:
json
{
"message": "Item created",
"item": {
"name": "Laptop",
"description": "A high-end gaming laptop",
"price": 1299.99,
"quantity": 5
}
}
🚀 关键点:
BaseModel
让 FastAPI 自动验证数据类型,并在 Swagger UI 显示接口文档。description
是可选字段(设定为None
)。
4. 路径参数 + 查询参数
你可以组合路径参数和查询参数,比如:
python
@app.get("/users/{user_id}")
async def get_user(user_id: int, detailed: bool = False):
if detailed:
return {"user_id": user_id, "details": "Full user details here"}
return {"user_id": user_id}
📌 测试方式:
http://127.0.0.1:8000/users/100
->{"user_id": 100}
http://127.0.0.1:8000/users/100?detailed=true
->{"user_id": 100, "details": "Full user details here"}
🚀 关键点:
user_id
是路径参数,必须提供。detailed
是查询参数,默认False
,可选提供。
5. 表单参数 (Form Parameters)
当你的 POST
请求是 application/x-www-form-urlencoded
时,需要 Form
来解析参数。
python
from fastapi import Form
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
📌 测试方式 : 用 POST
请求:
ini
username=admin&password=secret
返回:
json
{"username": "admin"}
🚀 关键点:
Form(...)
强制字段必填。- 适用于 HTML 表单提交数据的情况。
6. 文件上传参数
FastAPI 也支持上传文件:
python
from fastapi import File, UploadFile
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
📌 测试方式: 在 API 工具(如 Postman)上传文件,返回:
json
{"filename": "example.txt"}
🚀 关键点:
UploadFile
允许获取文件名、内容、MIME 类型等信息。
总结
参数类型 | 适用情况 | 示例 |
---|---|---|
路径参数 | URL 路径中的必需参数 | /items/{item_id} |
查询参数 | 可选参数,使用 ?key=value 形式 |
/search/?q=FastAPI&page=2 |
请求体参数 | 发送 JSON 数据 | POST /items/ |
路径+查询参数 | 结合两者 | /users/{user_id}?detailed=true |
表单参数 | application/x-www-form-urlencoded 表单提交 |
POST /login/ |
文件上传参数 | 上传文件 | POST /upload/ |
你可以根据自己的需求灵活运用不同的参数传递方式,现在试着在本地运行 FastAPI 代码,看看效果吧!🚀