Automatic router configuration for FastAPI based on filesystem structure.
pip install fastapi-auto-router- Create your router files in a directory structure that matches your desired API paths:
your_project/
└── routers/
└── user_management
├── users.py
└── {user_id}/
└── profile.py
- In your router files, create FastAPI routers:
routers/user_management/users.py
from fastapi import APIRouter
router = APIRouter()
@router.get("")
async def list_users():
return {"message": "List users"}- In your main FastAPI application, use AutoRouter:
from fastapi import FastAPI
from fastapi_auto_router import AutoRouter
app = FastAPI()
# Initialize and load routers
auto_router = AutoRouter(
app=app,
routers_dir="routers", # Path to your routers directory
api_prefix="/api/v1", # Optional: prefix for all routes
base_path=None # Optional: base path for resolving routers_dir (default: current working directory)
)
auto_router.load_routers()This will create the following routes:
/api/v1/user-management/users/api/v1/user-management/{user_id}/profile
- Automatic route configuration based on filesystem structure
- Converts underscores to hyphens in route paths
- Supports path parameters using {parameter_name} folders
- Customizable API prefix
- Flexible path resolution with
base_pathparameter - Works with any FastAPI application
The base_path parameter allows you to specify the directory where routers_dir is located. This is useful when your router files are not in the current working directory.
Behavior:
- If
routers_diris a relative path: the final path will bebase_path/routers_dir - If
routers_diris an absolute path:base_pathis ignored androuters_diris used as-is
Example:
from fastapi import FastAPI
from fastapi_auto_router import AutoRouter
from pathlib import Path
app = FastAPI()
# Use base_path to specify where routers directory is located
auto_router = AutoRouter(
app=app,
routers_dir="routers",
api_prefix="/api/v1",
base_path=str(Path(__file__).parent) # Resolve routers relative to current file
)
auto_router.load_routers()MIT License