APIRouter

APIRouter is used to separate API routes into different files. It helps keep large FastAPI projects organized.

Instead of putting all API routes inside one main.py file, you can create separate router files for different resources, such as users, products, orders, or authentication.

Code

routers/users.py

from fastapi import APIRouter

router = APIRouter(
    prefix="/users",
    tags=["Users"]
)


@router.get("/")
def get_users():
    return {
        "users": []
    }

The APIRouter is created with:

router = APIRouter(
    prefix="/users",
    tags=["Users"]
)

The prefix automatically adds /users to the routes defined inside the router.

The tags value is used to group the routes in the FastAPI API documentation.

Main Application

main.py

from fastapi import FastAPI
from routers.users import router

app = FastAPI()

app.include_router(router)

The router is imported into main.py:

from routers.users import router

Then it is included in the FastAPI application:

app.include_router(router)

This makes all routes defined inside the router available in the main application.

Project Structure

A simple project can be organized like this:

project/
│
├── main.py
│
└── routers/
    └── users.py

This approach becomes especially useful as the application grows and you have many different API routes.

Example Request

Because the router has this prefix:

prefix="/users"

and the route is:

@router.get("/")

the final endpoint becomes:

GET /users/

Output

{
    "users": []
}

Summary

APIRouter helps organize FastAPI applications by separating routes into different files.

For example:

router = APIRouter(
    prefix="/users",
    tags=["Users"]
)

Then include the router in the main application:

app.include_router(router)

This keeps the project structure clean and makes larger FastAPI applications easier to maintain.