Topics in this subject
FastAPI 2 min read Updated 11 Aug 2026

APIRouter (Structuring Apps)

Organizing large applications into manageable files and modules.

🧑‍🏫 Sabse pehle — simple mein samjho#

Jab app bada ho jata hai, tab saare routes (@app.get("/users"), @app.post("/items")) ek hi main.py file mein likhna bevkufi hai. File hazaaron line lambi ho jayegi aur manage nahi hogi. Node/Express mein hum express.Router() use karte the alag files banane ke liye. FastAPI mein hum APIRouter use karte hain. Tum users ke saare routes users.py mein rakhte ho, items ke items.py mein, aur fir sabko main.py mein ek sath connect (include) kar dete ho.

What is APIRouter?#

APIRouter acts like a "mini FastAPI application". It behaves exactly like the main app object, allowing you to define routes, dependencies, and tags, but it cannot be run on its own by Uvicorn. It must be attached to the main application.

1. Creating a Router File#

Let's create a separate file to handle all User-related operations.

routers/users.py

from fastapi import APIRouter

# Initialize the router
# The prefix ensures all routes inside here automatically start with /users
# Tags group these routes together in the Swagger Docs
router = APIRouter(
    prefix="/users",
    tags=["Users"]
)

# Notice we use @router instead of @app
@router.get("/")
async def read_users():
    return [{"username": "tarun"}, {"username": "rahul"}]

@router.get("/{user_id}")
async def read_user(user_id: int):
    return {"username": "tarun", "id": user_id}

2. Including the Router in Main#

Now we connect our new router to the main application file.

main.py

from fastapi import FastAPI
from routers import users # Import the users module

app = FastAPI()

# Attach the router to the main app
app.include_router(users.router)

@app.get("/")
async def root():
    return {"message": "Welcome to the main API"}

3. Applying Dependencies to an Entire Router#

What if you have an admin dashboard, and you want every single route inside the admin.py router to be protected by authentication? You don't have to add Depends() to every function! You can apply it to the entire router at once.

routers/admin.py

from fastapi import APIRouter, Depends
from dependencies import get_admin_token

# Any route defined under this router will automatically run get_admin_token first
router = APIRouter(
    prefix="/admin",
    tags=["Admin"],
    dependencies=[Depends(get_admin_token)]
)

@router.get("/dashboard")
async def admin_dashboard():
    # If they reach here, get_admin_token successfully validated them!
    return {"status": "all systems go"}