Mounting sub-applications under APIRouter #8682
Replies: 4 comments
-
|
As a work around, I can mount the sub application onto the root app and use the routers prefix app.mount(api_router.prefix + "/subapi", subapi)But is there a cleaner way to do this directly on the APIRouter instance? |
Beta Was this translation helpful? Give feedback.
-
@chriswhite199 There is not. The You can include routers inside of other routers and that will use the prefix. I have modified your example to show how to do this with routers: from fastapi import FastAPI, APIRouter
from starlette.testclient import TestClient
app = FastAPI()
api_router = APIRouter(prefix="/api")
@api_router.get("/app")
def read_main():
return {"message": "Hello World from main app"}
other_api_router = APIRouter(prefix="/subapi")
@other_api_router.get("/sub")
def read_sub():
return {"message": "Hello World from sub API"}
api_router.include_router(other_api_router)
app.include_router(api_router)
client = TestClient(app)
assert client.get('/api/app').status_code == 200
# this next assert fails
assert client.get('/api/subapi/sub').status_code == 200 |
Beta Was this translation helpful? Give feedback.
-
|
@STeveShary - Thanks for the response. I already have APIRouters included in other APIRouters to provide a hierarchy, but I was specifically looking for mounting sub-applications (to sort-of-reverse-proxy a number of other apps under a /api/proxy/ base path). In which case would it not be prudent to override the mount method in APIRouter (overriding the parent class's Router::mount method) and log.warning("There be dragons..") or raise a NotImplemented / some better exception? |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
First Check
Commit to Help
Example Code
Description
Is it possible to mount a sub-application under an APIRouter? APIRouter itself has a mount function and accepts similar arguments to mounting a sub-application on a FastAPI instance, but I can't get the routing to actually work (nor can i get the openapi docs or spec to come back from that I would assume are the correct URLs.
The docs for sub applications note that the sub-application will have it's root_path correctly set, and I've tried a few combinations of manually setting the root_path on the subapi instance, but to no avail.
Operating System
macOS
Operating System Details
No response
FastAPI Version
0.70.0
Python Version
3.9.7
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions