FastAPI回调未触发求助:回调请求未送达目标端点
FastAPI回调未触发问题解决
问题场景
你通过两个uvicorn服务模拟跨主机回调场景:
- 终端1启动服务:
uvicorn app:app --reload --port 8000 - 终端2启动服务:
uvicorn app:app --reload --port 12345 - 终端3调用接口:
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' "http://127.0.0.1:8000/process?callback_url=http://127.0.0.1:12345"
/process接口正常打印"Processing input...",但12345端口的回调端点始终无输出。
核心问题
FastAPI的callbacks参数仅用于生成OpenAPI文档中的回调规范,不会自动发起HTTP请求到回调地址。你的代码只定义了回调的接口结构,但没有编写实际发送回调请求的逻辑。
解决步骤
- 安装HTTP请求库
httpx(FastAPI官方推荐用于异步/同步请求):
pip install httpx
- 修改代码,在
/process接口中添加发送回调请求的逻辑:
from fastapi import APIRouter, FastAPI, HTTPException from pydantic import BaseModel, HttpUrl import httpx app = FastAPI() class Input(BaseModel): name: str class Output(BaseModel): message: str callback_router = APIRouter() @callback_router.post("{$callback_url}/callback") def process_notification(body: Output) -> None: pass @app.post("/process", response_model=Output, callbacks=callback_router.routes) def process(input: Input, callback_url: HttpUrl | None) -> Output: print("Processing input...") message = f"Hello, {input.name}!" output_data = Output(message=message) # 新增:发送回调请求 if callback_url: try: # 同步发送POST请求到回调地址 with httpx.Client() as client: response = client.post( url=f"{callback_url}/callback", json=output_data.dict() ) response.raise_for_status() # 检查请求是否成功 print(f"Callback sent successfully, status code: {response.status_code}") except httpx.HTTPError as e: raise HTTPException(status_code=500, detail=f"Failed to send callback: {str(e)}") return output_data @app.post("/callback") def callback(output: Output) -> str: print("Callback received...") message = f"it said {output.message}" return message
关键说明
- 新增的
httpx.Client代码负责实际向callback_url + "/callback"发送POST请求,把生成的Output数据作为JSON体传递 - 添加了异常捕获,避免回调失败导致主接口报错(可根据业务需求调整异常处理逻辑)
- 如果你用异步接口,可替换为
httpx.AsyncClient并使用async/await语法
验证
重新启动两个服务,执行curl命令后:
- 8000端口终端会打印"Processing input..."和"Callback sent successfully..."
- 12345端口终端会打印"Callback received..."
内容的提问来源于stack exchange,提问作者tailaiw
相关产品推荐
相关产品推荐

