Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI import routers from separate file

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?

like image 200
Adithya Samavedhi Avatar asked Sep 17 '26 16:09

Adithya Samavedhi


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

like image 160
Ryuujo Avatar answered Sep 19 '26 05:09

Ryuujo