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

如何在运行中的FastAPI服务器动态添加带UUID的API端点?

问题描述

现有一段FastAPI代码,通过handle_get_endpoints函数将/api/create_game端点与外部文件中的create_new_game函数绑定。需要实现:当调用/api/create_game接口时,create_new_game函数生成一个带唯一UUID的新API端点,并将该端点注册到当前正在运行的FastAPI服务器中。

原代码示例:

from api.server.create_new_game import create_new_game

app = FastAPI()

def handle_get_endpoints(app, endpoint, function):
    @app.get(endpoint)
    async def handle_endpoint():
        return function()

handle_get_endpoints(app, "/api/create_game", create_new_game)
uvicorn.run(app, host="0.0.0.0", port=8000)
实现方案

FastAPI支持通过app.add_api_route()方法动态注册路由,结合UUID生成唯一端点路径,即可实现需求。具体步骤如下:

1. 修改create_new_game函数逻辑

在api/server/create_new_game.py文件中,导入必要模块,生成唯一UUID,定义新端点的处理逻辑并完成注册:

import uuid
from fastapi import FastAPI

def create_new_game(app: FastAPI):
    # 生成唯一UUID作为新端点的路径标识
    game_uuid = str(uuid.uuid4())
    new_endpoint = f"/api/game/{game_uuid}"

    # 定义新端点的处理函数
    async def game_endpoint():
        return {"game_id": game_uuid, "message": "游戏已创建,此为专属访问端点"}

    # 动态将新端点注册到FastAPI应用
    app.add_api_route(path=new_endpoint, endpoint=game_endpoint, methods=["GET"])

    # 返回新端点的URL给调用方
    return {"new_game_endpoint": new_endpoint}

2. 调整主文件的绑定逻辑

主文件需要将app实例传递给create_new_game函数,确保动态注册路由的操作能生效:

from api.server.create_new_game import create_new_game
from fastapi import FastAPI
import uvicorn

app = FastAPI()

def handle_get_endpoints(app, endpoint, function):
    @app.get(endpoint)
    async def handle_endpoint():
        # 把app对象传入create_new_game,用于动态注册路由
        return function(app)

handle_get_endpoints(app, "/api/create_game", create_new_game)

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)

3. 验证效果

启动服务后,调用GET /api/create_game接口,会返回类似如下的响应:

{"new_game_endpoint": "/api/game/123e4567-e89b-12d3-a456-426614174000"}

直接访问返回的这个新端点,就能获取到该端点的响应内容。

注意事项
  • 动态注册的路由会在服务运行期间持续存在,重启服务后会丢失。如果需要持久化这些路由,需结合数据库存储路由信息,在服务启动时重新注册。
  • 若新端点需要更复杂的业务逻辑,可以扩展game_endpoint函数,比如添加参数接收、POST请求处理等。
  • 必须确保create_new_game函数能正确获取到FastAPI的app实例,否则无法完成动态路由注册。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 20:40:10