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

如何将多端口FastAPI实例的Redoc整合到单个页面?

整合多端口FastAPI实例的Redoc到统一页面的方法

核心思路

通过一个新的FastAPI聚合服务,抓取各个实例的OpenAPI JSON文档并合并,再挂载Redoc组件展示统一的API文档页面。


具体实现步骤

1. 创建聚合FastAPI服务(端口8004)

创建一个新的Python文件(比如unified_redoc.py),编写以下代码:

from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
import requests

# 初始化聚合服务,端口启动后设为8004
app = FastAPI(title="统一API文档", version="1.0")

# 配置需要聚合的FastAPI实例地址列表
TARGET_APIS = [
    "http://127.0.0.1:8000",
    "http://127.0.0.1:8001"
]

def fetch_remote_openapi(api_url: str):
    """获取远程FastAPI实例的OpenAPI JSON文档"""
    try:
        resp = requests.get(f"{api_url}/openapi.json", timeout=5)
        resp.raise_for_status()
        return resp.json()
    except requests.RequestException as e:
        raise HTTPException(status_code=500, detail=f"获取实例 {api_url} 文档失败: {str(e)}")

def merge_openapi_docs():
    """合并多个OpenAPI文档"""
    merged = {
        "openapi": "3.0.2",
        "info": {"title": "统一API文档", "version": "1.0.0"},
        "paths": {},
        "components": {"schemas": {}, "securitySchemes": {}}
    }

    for idx, api_url in enumerate(TARGET_APIS):
        remote_doc = fetch_remote_openapi(api_url)
        # 为每个实例的路径添加前缀,避免端点冲突
        prefix = f"/service{idx+1}"
        prefixed_paths = {}
        for path, ops in remote_doc.get("paths", {}).items():
            prefixed_paths[f"{prefix}{path}"] = ops
        merged["paths"].update(prefixed_paths)

        # 合并数据模型和安全方案
        merged["components"]["schemas"].update(
            remote_doc.get("components", {}).get("schemas", {})
        )
        merged["components"]["securitySchemes"].update(
            remote_doc.get("components", {}).get("securitySchemes", {})
        )
    
    return merged

# 提供合并后的OpenAPI JSON接口
@app.get("/openapi.json", include_in_schema=False)
async def get_unified_openapi():
    return merge_openapi_docs()

# 挂载Redoc页面
@app.get("/redoc", include_in_schema=False, response_class=HTMLResponse)
async def unified_redoc():
    return """
    <!DOCTYPE html>
    <html>
    <head>
        <title>统一Redoc文档</title>
        <script src="https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js"></script>
    </head>
    <body>
        <redoc spec-url='/openapi.json'></redoc>
    </body>
    </html>
    """

2. 配置原FastAPI实例的CORS(跨域访问)

如果聚合服务和原实例不在同一域名/端口,需要在每个原FastAPI实例中添加CORS中间件,允许聚合服务访问:

from fastapi.middleware.cors import CORSMiddleware

# 原实例的FastAPI app对象
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://127.0.0.1:8004"],
    allow_methods=["*"],
    allow_headers=["*"],
)

3. 启动服务并验证

  • 启动所有原FastAPI实例(8000、8001端口)
  • 启动聚合服务:uvicorn unified_redoc:app --host 127.0.0.1 --port 8004
  • 访问http://127.0.0.1:8004/redoc,即可看到所有实例的API端点统一展示

注意事项

  • 端点冲突处理:如果多个实例存在相同路径的端点,合并后会覆盖为最后一个实例的内容,建议通过添加前缀(如代码中/service1、/service2)避免冲突。
  • 文档实时性:每次访问聚合Redoc页面时,都会重新抓取原实例的OpenAPI文档,确保内容是最新的。
  • 性能优化:如果原实例较多或文档较大,可以添加缓存机制,减少重复请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:27:45