How to Use Prefix in Router FastAPI for Organized Routes
In FastAPI, you use the
prefix parameter when creating an APIRouter to add a common path prefix to all routes in that router. This helps organize routes under a shared URL segment, like /items, making your API cleaner and easier to manage.Syntax
The prefix parameter is used when creating an APIRouter instance. It sets a common path prefix for all routes added to that router.
- APIRouter(prefix="/prefix_path"): Creates a router with a path prefix.
- @router.get("/subpath"): Defines a route under the prefix.
- app.include_router(router): Adds the router to the main FastAPI app.
python
from fastapi import FastAPI, APIRouter router = APIRouter(prefix="/items") @router.get("/") async def read_items(): return {"message": "List of items"} app = FastAPI() app.include_router(router)
Example
This example shows how to create a router with the prefix /items. All routes inside this router will start with /items. The main app includes this router, so accessing /items/ returns the list of items.
python
from fastapi import FastAPI, APIRouter router = APIRouter(prefix="/items") @router.get("/") async def read_items(): return {"items": ["apple", "banana", "cherry"]} app = FastAPI() app.include_router(router) # Run with: uvicorn filename:app --reload
Output
GET /items/ --> {"items": ["apple", "banana", "cherry"]}
Common Pitfalls
Common mistakes when using prefix include:
- Forgetting to include the router in the main app with
include_router(). - Adding a leading slash in route paths inside the router is optional but be consistent.
- Not realizing the prefix applies to all routes, so duplicate prefixes cause incorrect URLs.
python
from fastapi import FastAPI, APIRouter # Wrong: forgetting prefix router = APIRouter() @router.get("/items") # This route will be at /items, no prefix async def read_items(): return {"message": "No prefix used"} app = FastAPI() app.include_router(router) # Right: use prefix to group routes router2 = APIRouter(prefix="/items") @router2.get("/") # This route is at /items/ async def read_items2(): return {"message": "With prefix"} app.include_router(router2)
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| prefix | Adds a common path prefix to all routes in the router | `APIRouter(prefix='/items')` |
| include_router | Includes the router in the main FastAPI app | `app.include_router(router)` |
| route path | Defines the path relative to the prefix | `@router.get('/')` for '/items/' |
| multiple routers | Use different prefixes to organize routes | `APIRouter(prefix='/users')` |
Key Takeaways
Use the prefix parameter in APIRouter to group routes under a common URL path.
Include the router in the main FastAPI app with include_router to activate routes.
Route paths inside the router are relative to the prefix, so avoid duplicating prefixes.
Prefixes help keep your API organized and easier to maintain.
Be consistent with leading slashes in route paths inside routers.