You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI运行时新增端点后,如何重新生成OpenAPI Schema并更新文档?

解决FastAPI运行时添加路由后OpenAPI文档不更新的问题

FastAPI默认会缓存生成的OpenAPI Schema,所以用add_api_route动态添加路由后,/docs页面不会自动刷新显示新端点,解决方法如下:

1. 强制每次请求重新生成OpenAPI Schema

通过自定义openapi方法,每次调用时清空缓存并重新生成Schema,确保包含最新路由:

from fastapi import FastAPI
from fastapi.openapi.utils import get_openapi

app = FastAPI(title="API Gateway", version="1.0.0")

# 自定义OpenAPI生成逻辑
def refresh_openapi():
    # 清空已缓存的Schema
    app.openapi_schema = None
    # 基于当前所有路由重新生成Schema
    return get_openapi(
        title=app.title,
        version=app.version,
        description=app.description,
        routes=app.routes,
    )

# 替换默认的openapi生成方法
app.openapi = refresh_openapi

# 初始测试路由
@app.get("/")
async def root():
    return {"msg": "API Gateway Root"}

# 模拟Auth服务触发动态添加路由
def add_auth_endpoint():
    # 编写转发到Auth服务的逻辑(示例用httpx做反向代理)
    import httpx
    async def auth_proxy():
        async with httpx.AsyncClient() as client:
            resp = await client.get("http://Auth/your_auth_endpoint")
            return resp.json()
    
    # 动态添加端点
    app.add_api_route("/new_endpoint", auth_proxy, methods=["GET"])

# 调用添加路由
add_auth_endpoint()

2. 手动触发Schema刷新

如果不需要每次请求都重新生成,也可以在动态添加路由后,手动清空缓存的Schema:

# 动态添加路由后执行
app.openapi_schema = None

这样下次访问/docs或/openapi.json时,FastAPI会自动重新生成包含新端点的Schema。

关于流量转发的实现

动态添加的端点可以通过httpx(异步HTTP客户端)实现反向代理,将请求转发到Auth服务对应的端点,示例代码如上。需要注意处理请求参数、请求体、响应状态码等,确保转发逻辑完整。

内容的提问来源于stack exchange,提问作者Dmitriy Kalekin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 16:30:45