Hi folks,
I’m developing a FastAPI application and would like to place a bunch of APIRouter instances in a directory. I don’t want to manually import each of the routers. I have found a way to make it dynamic, but it is a bit of an eyesore:
# routers/__init__.py
from importlib import import_module
import pkgutil
from pathlib import Path
from fastapi import APIRouter
routers: list[APIRouter] = []
for module in pkgutil.walk_packages([Path(__file__).absolute().parent]):
routers.append(import_module(f".{module.name}", __package__).router)
This seems like a hack, and I doubt I will be able to understand what it does in 3 years. Is there a better way?
Thanks!