1

I would like to set up sub applications in my FastAPI project. I have my root file which contains the configuration and a "routes" folder where my routes are organized in different files.

main.py

app = FastAPI()


@app.get("/app")
def read_main():
    return {"message": "Hello World from main app"}


subapi = FastAPI()


@subapi.get("/sub")
def read_sub():
    return {"message": "Hello World from sub API"}


app.mount("/subapi", subapi)

This works, I have access to the FastAPI docs localhot:8000/docs and localhost:8000/subapi with my respective routes.

However, when I call a route in my file routes/session.py

from app.main import subapi

@subapi.post(/session)

this route /session does not appear in the doc and when I test with curl I get a 404 error.

Am I forced to put all my controllers in my main.py file?

Can someone help me please?

Chris
  • 18,724
  • 6
  • 46
  • 80
Marine
  • 65
  • 1
  • 8
  • Are you actually importing `routes/session.py` anywhere? i.e. does the code get run? Remember that code doesn't magically run in any file unless you're actually importing the file. Are you opening the docs under `/subapi/docs`? – MatsLindh Apr 26 '23 at 14:27
  • No it's true I didn't import it in my main.py file but how can I import it since I don't use include_router? Yes I have access /subapi/docs – Marine Apr 26 '23 at 14:41
  • `import projectname.subapi` - which will have to be after you've defined subapi in app.py in your example. But a better layout would be to declare `subapi = FastAPI()` in your `subapi.py` file, then import `subapi` from `projectname.subapi` and mount it in your app.py - that would avoid the circular dependency. – MatsLindh Apr 26 '23 at 19:32

0 Answers0