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?
Sure, you can do that.
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With