如何在 FastAPI 中列出所有定义的 URL 路径?

JPG*_*JPG 4 python python-3.x fastapi

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

JPG*_*JPG 10

要获取所有可能的 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
Run Code Online (Sandbox Code Playgroud)


小智 9

我试图编辑原始答案,但不让我这么做。

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

主要.py
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)

Run Code Online (Sandbox Code Playgroud)

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

实用程序.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
Run Code Online (Sandbox Code Playgroud)

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