English 中文(简体)
FastAPI - Mounting A Sub-App
  • 时间:2024-12-22

FastAPI - Mounting a Sub-App


Previous Page Next Page  

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-apppcation. The app.mount() method adds another completely "independent" apppcation in a specific path of the main app. It then takes care of handpng everything under that path, with the path operations declared in that sub-apppcation.

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


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

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


subapp = FastAPI()
@subapp.get("/sub")
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 apppcation.


app.mount("/subapp", subapp)

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

FastAPI Mounting a Sub-App

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

FastAPI Mounting a Sub-App Advertisements