diff --git a/README.md b/README.md index 723606c..404928a 100644 --- a/README.md +++ b/README.md @@ -266,6 +266,44 @@ async def read_root(request: Request) -> dict[str, Any]: return response.json() ``` +## 7. Use a main router to group all sub-routers instead of using the `app` directly + +Instead of using the `app` directly, you can use a main router to group all sub-routers. + +```py +# project/api/__init__.py +from fastapi import APIRouter + +from project.routers.account import account +from project.routers.admin import admin + +main = APIRouter(prefix="/api") + +main.include_router(account) +main.include_router(admin) +``` + +```py +# project/main.py +from fastapi import FastAPI + +from project.api import api_router + + +app = FastAPI() + +app.include_router(api_router) + +# And many other configurations... +``` + +This way, you can keep your `main.py` file short and clean. The configuration of the app +will be in the `main.py` file, and the management of the routers will be in the +`api` package. + +This is really useful when you have feature flag logic that include a router or not. +This code won't bloat the `main.py` file and will be easier to maintain. + [uvicorn]: https://www.uvicorn.org/ [run_sync]: https://anyio.readthedocs.io/en/stable/threads.html#running-a-function-in-a-worker-thread [run_in_threadpool]: https://github.com/encode/starlette/blob/9f16bf5c25e126200701f6e04330864f4a91a898/starlette/concurrency.py#L36-L42