Including routers helps organize your FastAPI app by splitting routes into smaller parts. This makes your code cleaner and easier to manage.
0
0
Including routers in main app in FastAPI
Introduction
You want to separate user-related routes from product-related routes.
Your app is growing and you want to keep code organized in different files.
You want to reuse routes in multiple apps or projects.
You want to group routes by functionality or feature.
You want to keep your main app file simple and focused.
Syntax
FastAPI
from fastapi import FastAPI from some_router_file import router app = FastAPI() app.include_router(router, prefix="/prefix", tags=["tag"])
The include_router method adds routes from another file or module.
You can add a prefix to group routes under a common path.
Examples
This adds all user routes under the
/users path with a tag for documentation.FastAPI
from fastapi import FastAPI from users import router as users_router app = FastAPI() app.include_router(users_router, prefix="/users", tags=["users"])
This includes product routes without any prefix, so they appear at their original paths.
FastAPI
from fastapi import FastAPI from products import router as products_router app = FastAPI() app.include_router(products_router)
Sample Program
This example creates a user router with two routes. Then it includes the router in the main app under the /users path. When you visit /users/, you get the list of users. When you visit /users/1, you get user 1's info.
FastAPI
from fastapi import FastAPI, APIRouter # Create a router for user routes user_router = APIRouter() @user_router.get("/") async def read_users(): return {"message": "List of users"} @user_router.get("/{user_id}") async def read_user(user_id: int): return {"message": f"User {user_id}"} # Main app app = FastAPI() # Include the user router with prefix app.include_router(user_router, prefix="/users", tags=["users"])
OutputSuccess
Important Notes
Use prefix to avoid route conflicts and group related routes.
Tags help organize your API docs automatically in Swagger UI.
Routers keep your code modular and easier to maintain as your app grows.
Summary
Including routers splits your app into smaller, manageable parts.
Use include_router with optional prefix and tags.
This helps keep your code clean and your API organized.