【问题标题】:How can I list all defined URL paths in FastAPI?如何在 FastAPI 中列出所有已定义的 URL 路径?
【发布时间】:2020-08-01 14:29:35
【问题描述】:

假设我有一个包含 100 多个 API 端点的 FastAPI 项目。 如何列出所有 API/路径?

【问题讨论】:

    标签: python python-3.x fastapi


    【解决方案1】:

    要获取所有可能的 URL 模式,我们需要访问 定义的 URL 路由,这是正在运行的应用实例的属性。

    我们至少可以通过两种方式做到这一点,

    1. 使用 FastAPI 应用程序:当您可以访问 FastAPi 实例时,这很方便
    2. 使用 Request 实例:当您可以访问传入请求但不能访问 FastAPI 实例时,这很方便。

    完整示例

    from fastapi import FastAPI, Request
    
    app = FastAPI()
    
    
    @app.get(path="/", name="API Foo")
    def foo():
        return {"message": "this is API Foo"}
    
    
    @app.post(path="/bar", name="API Bar")
    def bar():
        return {"message": "this is API Bar"}
    
    
    # Using FastAPI instance
    @app.get("/url-list")
    def get_all_urls():
        url_list = [{"path": route.path, "name": route.name} for route in app.routes]
        return url_list
    
    
    # Using Request instance
    @app.get("/url-list-from-request")
    def get_all_urls_from_request(request: Request):
        url_list = [
            {"path": route.path, "name": route.name} for route in request.app.routes
        ]
        return url_list

    【讨论】:

      【解决方案2】:

      我试图提供对原始答案的编辑,但不让我这样做。

      另一个用例:假设您不在主应用程序文件中,并且无权访问命名空间中的app。在这种情况下,Starlette 文档说我们还可以从request.app 的请求中访问应用程序实例。例如,如果在主文件中您只有应用程序实例,并且不希望在主文件中有任何端点,但所有端点都位于单独的路由器中。

      主文件
      from fastapi import FastAPI
      # then let's import all the various routers we have
      # please note that api is the name of our package
      from api.routers import router_1, router_2, router_3, utils
      app = FastAPI()
      
      app.include_router(router_1)
      app.include_router(router_2)
      app.include_router(router_3)
      app.include_router(utils)
      
      

      我在 utils 路由器中有我的 list_endpoints 端点。为了能够列出所有应用程序路由,我将执行以下操作:

      实用程序.py
      from fastapi import APIRouter, Request
      
      router = APIRouter(
          prefix="/utils",
          tags=["utilities"]
      )
      
      @router.get('/list_endpoints/')
      def list_endpoints(request: Request):
          url_list = [
              {'path': route.path, 'name': route.name}
              for route in request.app.routes
          ]
          return url_list
      

      请注意,我没有使用app.routes,而是使用了request.app.routes,并且我可以访问所有这些。如果您现在访问/utils/list_endpoints,您将获得所有路线。

      【讨论】:

      • 感谢您的回答。顺便说一句,我已经用你的建议更新了 OP。
      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 2022-11-20
      • 2022-06-17
      • 2021-05-27
      • 2021-02-11
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      相关资源
      最近更新 更多