import importlib.util from pathlib import Path from fastapi import APIRouter def load_endpoints(base_path: Path = Path("endpoints")) -> APIRouter: router = APIRouter() for file_path in base_path.glob("**/*.*.py"): # Parse path components relative_path = file_path.relative_to(base_path) path_parts = list(relative_path.parts) # Extract HTTP method from filename filename = path_parts[-1] name_parts = filename.split(".") if len(name_parts) < 3 or name_parts[-1] != "py": continue # Skip invalid formats method = name_parts[-2].upper() endpoint_name = ".".join(name_parts[:-2]) # Build URL path url_path = "/" + "/".join(path_parts[:-1] + [endpoint_name]) url_path = url_path.replace("[", "{").replace("]", "}") # Convert path params # Load the module spec = importlib.util.spec_from_file_location("", file_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # Find the router in the module if hasattr(module, "router"): router.include_router(module.router, prefix=url_path) return router