FastAPI 中定义接口函数参数,包含请求体参数、查询参数、依赖注入参数的组合。
✅ 示例结构
async def chat(request: Request,data: ChatData,conversation_id: Optional[str] = Query(None),current_user: User = Depends(get_current_user),
):
这表示你定义了一个 异步(async) 的 HTTP 接口函数 chat
,它会自动被 FastAPI 接收到请求时调用。
1️⃣ request: Request
✅ 作用:
- 表示接收到的原始 HTTP 请求对象。
- 你可以通过
request
拿到请求头、IP、路径、cookie 等。
🧠 举例:
ip = request.client.host # 获取用户 IP 地址
ua = request.headers.get("user-agent") # 获取浏览器信息
2️⃣ data: ChatData
✅ 作用:
- 从请求体中自动解析并验证一个 JSON 数据,转换为
ChatData
类型(你自定义的 Pydantic 模型)。
🔥 FastAPI 会自动:
- 检查字段类型是否匹配。
- 自动报错 + 返回 HTTP 422,如果数据格式不对。
🧠 举例:
你传 JSON 请求体:
{"messages": [{"role": "user", "content": "今天天气怎么样?"}],"data": {"doc_ids": ["doc1"]}
}
FastAPI 会自动转换为:
data.messages[0].content == "今天天气怎么样?"
data.data["doc_ids"] == ["doc1"]
3️⃣ conversation_id: Optional[str] = Query(None)
✅ 作用:
- 表示这个参数是从查询参数(URL 的 ? 后面)中读取的。
- 类型是可选字符串,如果没传就默认为
None
。
🔥 举例:
你访问的是:
POST /chat?conversation_id=abc123
那么:
conversation_id == "abc123"
如果没有 ?conversation_id=...
,那就是 None
。
4️⃣ current_user: User = Depends(get_current_user)
✅ 作用:
- 这是 FastAPI 的 依赖注入机制(Depends)。
- 表示调用你定义好的函数
get_current_user()
来获取当前用户身份。 - 返回值会自动赋值给
current_user
,类型为User
。
🔥 举例:
你的 get_current_user()
方法会根据请求的 token 验证并返回用户对象,如:
def get_current_user():return User(id="u123", username="张三")
那么你可以直接用:
print(current_user.username) # 张三
📌 总结表格
参数名 | 来源 | 类型 | 默认值 | 作用 |
---|---|---|---|---|
request | 自动注入 | FastAPI 的 Request 类型 | 无 | 获取请求头、路径、客户端信息等 |
data | 请求体 JSON | ChatData Pydantic 模型 | 无 | 解析用户请求数据,自动验证字段类型 |
conversation_id | 查询参数 ?conversation_id=xxx | Optional[str] | None | 标识多轮对话 ID |
current_user | 依赖注入 Depends | User(你定义的用户模型) | 由函数返回 | 自动获取当前用户身份信息 |
🌰 综合调用举例:
你发起一个请求:
POST /chat?conversation_id=abc123
Content-Type: application/json
Authorization: Bearer <你的token>{"messages": [{"role": "user", "content": "帮我总结一下这段文章"}],"data": {"doc_ids": ["doc1", "doc2"]}
}
后台就会自动执行:
- 调用
get_current_user()
把你 token 解析成用户对象 - 把 JSON 转为
ChatData
对象 - 把
conversation_id
解析出来变成参数