FastAPI - Mounting a Sub-App

If you have two independent FastAPI apps, one of them can be mounted on top of the other. The one that is mounted is called a sub-application. The app.mount() method adds another completely "independent" application in a specific path of the main app. It then takes care of handling everything under that path, with the path operations declared in that sub-application.

Let us first declare a simple FastAPI application object to be used as a top level application.

from fastapi import FastAPI
app = FastAPI()
def mainindex():
   return {"message": "Hello World from Top level app"}

Then create another application object subapp and add its own path operations.

subapp = FastAPI()
def subindex():
   return {"message": "Hello World from sub app"}

Mount this subapp object on the main app by using mount() method. Two parameters needed are the URL route and name of the sub application.

app.mount("/subapp", subapp)

Both the main and sub application will have its own docs as can be inspected using Swagger UI.

FastAPI Mounting a Sub-App

The sub application’s docs are available at http://localhost:8000/subapp/docs

FastAPI Mounting a Sub-App