Skip to content

Instantly share code, notes, and snippets.

@TheOnlyWayUp
Created September 3, 2023 15:11
Show Gist options
  • Save TheOnlyWayUp/f947df4a369a27133a44cf915a39be37 to your computer and use it in GitHub Desktop.
Save TheOnlyWayUp/f947df4a369a27133a44cf915a39be37 to your computer and use it in GitHub Desktop.
FastAPI Router Loader

Assuming you have a folder beside your main.py called ./routes, in which you have your router files (must include a router variable, which is likely your fastapi.APIRouter instance.)

This main.py script loads in all your routes.

Throwing it on here so I can find it later, might be helpful to you guys as well.

Files prefixed with nr_, for example, nr_database.py, are ignored by the script. nr standing for not router.

TheOnlyWayUp © 2023

from fastapi import FastAPI
from pathlib import Path
app = FastAPI(docs_url="/docs", redoc_url="/redoc") # TODO: Remove when production
routes_folder = Path(__file__).parent / "routes"
routes = []
for route_file in routes_folder.glob("*py"):
if route_file.stem.startswith("nr_"):
continue
exec(f"from routes.{route_file.stem} import router")
routes.append(router) # type: ignore
del router # type: ignore
# don't fix what's not broken 🤷
for router in routes:
app.include_router(router)
# --- #
if __name__ == "__main__":
import uvicorn
uvicorn.run("main:app", host="0.0.0.0", port=80, reload=True)
# 🙏
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment