
1. 路径参数数据位置直接嵌入在URL的路径中。用途通常用于定位特定的资源。它是必填的因为它是URL结构的一部分。示例/users/{user_id}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?page2limit10from fastapi import FastAPI app FastAPI() fake_items_db [{item_name: Foo}, {item_name: Bar}, {item_name: Baz}] # 请求地址/items?skip0limit10 app.get(/items/) async def list_items(skip: int 0, limit: int 10): # skip 和 limit 是查询参数 return fake_items_db[skip : skip limit] # 可选参数的例子/users?nameJohn 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}。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}