How to get a list of mounted sub applications from a FastAPI app?

144 Views Asked by At

I have a FastAPI app with a few mounted sub applications, and would like to know if there is a app.subapps() or similar method to give me the instances of sub applications mounted to the main app.

Thanks

1

There are 1 best solutions below

2
On BEST ANSWER

Every app that is mounted into another application is added to the application's routes as a mounted route.

We can therefor iterate over the registered routes and keep those that are instances of the Mount object.

from fastapi import FastAPI
from starlette.routing import Mount

app = FastAPI()
app2 = FastAPI()

@app2.get("/")
def app2ish():
    return {"version": "app2"}

app.mount("/app2", app2)


@app.get("/")
async def app1ish():
    return {"version": "app"}

    

def get_mounted_apps(app):
    return [
        route.app
        for route in app.router.routes
        if isinstance(route, Mount)
    ]

    
print(get_mounted_apps(app))

This outputs:

[<fastapi.applications.FastAPI object at 0x00000224FFDEFC70>]