1. 路径参数
-
数据位置:直接嵌入在URL的路径中。
-
用途 :通常用于定位特定的资源。它是必填的,因为它是URL结构的一部分。
-
示例 :
/users/{user_id}
python
from fastapi import FastAPI
app = FastAPI()
# 假设我们要获取ID为123的用户
# 请求地址:/users/123
@app.get("/users/{user_id}")
async def read_user(user_id: int): # user_id 是路径参数
return {"user_id": user_id}
2. 查询参数
-
数据位置 :URL中
?后面的部分,以键值对形式存在。 -
用途 :通常用于过滤、排序、分页 或提供可选的额外指令。它是可选的(通常有默认值),或者是非必须的。
-
示例 :
/users?page=2&limit=10
python
from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
# 请求地址:/items?skip=0&limit=10
@app.get("/items/")
async def list_items(skip: int = 0, limit: int = 10): # skip 和 limit 是查询参数
return fake_items_db[skip : skip + limit]
# 可选参数的例子:/users?name=John
@app.get("/users/")
async def get_user(name: str = None): # name 是可选查询参数
if name:
return f"查询名为 {name} 的用户"
return "返回所有用户"
3. 请求体参数
-
数据位置 :HTTP请求的**Body(主体)**中。
-
用途 :通常用于提交创建或更新资源的数据。由于Body可以传输复杂的结构,它适合传输较复杂的数据(如嵌套的JSON对象)。
-
示例 :在POST请求的Body中放置
{"name": "Foo", "price": 45.2}。
python
from fastapi import FastAPI
from pydantic import BaseModel # 需要定义数据模型
app = FastAPI()
# 1. 定义一个 Pydantic 模型,描述请求体的结构
class Item(BaseModel):
name: str
price: float
is_offer: bool = False # 可选字段,默认False
# 2. 在路径操作函数中使用该模型
@app.post("/items/")
async def create_item(item: Item): # item 是请求体参数
# FastAPI 会读取请求体,并验证是否符合 Item 模型的格式
return {"item_name": item.name, "item_price": item.price}