3

I am trying to import routers from a separate file instead of mentioning app.include_router() for each router in the FastAPI app file. I want to avoid the include router statement for each router in the main file and would like to split it into another file. I would like to include the routers in a separate file. Is this possible?

  • 1
    There is nothing limiting you from having `from .main import app` in a `routes.py`, and then having `import .routes` at the end of `main.py` (i.e. importing a file that populates the routes in your app after defining your app). Would that work? – MatsLindh Nov 30 '21 at 11:05

1 Answers1

2

Sure, you can do that.

for static import (normal cases)

From your app/routes/__init__.py, you can try

import route1
import route2
import route3
__all__ = ['route1', 'route2', 'route3']

You could even do without defining all, but things (pydoc, if nothing else) will work more cleanly if you define it, even if it's just a list of what you imported.

(for dynamic import and more over: How to import all submodules?)

Ryuujo
  • 97
  • 9