Skip to content

🔀 Add "Use a main router" advice #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down