FastAPI import routers from separate file

Viewed 677

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 Answers

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?)

Related