On this page

Modularizing a FastAPI App with APIRouter

Published on August 10, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A single main.py file works fine for a handful of routes, but it stops being manageable once an app covers several unrelated resources — tasks, users, authentication — each with their own model and set of endpoints tangled together in one file. APIRouter is FastAPI's tool for splitting that apart: it behaves like a smaller version of the main app, with its own routes registered on it independently, and gets wired into the real app with a single line once it's ready.

The MDN reference on HTTP response status codes is worth having open alongside this — several of the routes below return specific status codes deliberately, and knowing what each one signals makes the reasoning behind those choices easier to follow.


Why Modularize​

The core problem a single growing main.py runs into isn't length by itself — it's that unrelated concerns end up living in the same file with no boundary between them. Splitting a task-related model from a user-related one, or a task endpoint from an authentication endpoint, makes each piece testable and readable in isolation, and makes it possible to reuse a router's logic elsewhere without dragging in code that has nothing to do with it. This is also what lets a team divide work along the same lines — one person's changes to routers/tasks.py have no reason to conflict with another's changes to routers/users.py if the two were never sharing a file to begin with.


What APIRouter Does​

APIRouter is imported from fastapi and instantiated the same way an FastAPI() app is, with its own @router.get, @router.post, and other method decorators available on it. Routes registered on a router don't do anything on their own until that router is mounted into the main app — which is the final step covered further down, and the one that actually makes its routes reachable.


Restructuring the Project​


task_manager/

├── main.py

├── models/

│   ├── __init__.py

│   └── task.py

└── routers/

    ├── __init__.py

    └── tasks.py

__init__.py files inside models/ and routers/ are what turn those folders into proper Python packages rather than just directories that happen to contain .py files — this is what makes an import like from models.task import Task resolve reliably. The files can be left empty; their presence is what matters, not their content.


Defining the Task Model​

models/task.py:


from pydantic import BaseModel

from typing import Optional



class Task(BaseModel):

    title: str

    description: Optional[str] = None

    completed: bool = False

This is the same model a single-file version of the app would define directly in main.py — moving it into its own file changes nothing about how it behaves, only where it lives.


Building the Task Router​

routers/tasks.py:


from fastapi import APIRouter, HTTPException

from models.task import Task



router = APIRouter(prefix="/tasks", tags=["Tasks"])



tasks = {}

task_id_counter = 1



@router.post("", status_code=201)

def create_task(task: Task):

    global task_id_counter

    task_data = task.model_dump()

    task_data["id"] = task_id_counter

    tasks[task_id_counter] = task_data

    task_id_counter += 1

    return task_data



@router.get("")

def get_all_tasks():

    return list(tasks.values())



@router.get("/{task_id}")

def get_task(task_id: int):

    if task_id not in tasks:

        raise HTTPException(status_code=404, detail="Task not found")

    return tasks[task_id]



@router.put("/{task_id}")

def update_task(task_id: int, updated_task: Task):

    if task_id not in tasks:

        raise HTTPException(status_code=404, detail="Task not found")

    task_data = updated_task.model_dump()

    task_data["id"] = task_id

    tasks[task_id] = task_data

    return task_data



@router.delete("/{task_id}", status_code=204)

def delete_task(task_id: int):

    if task_id not in tasks:

        raise HTTPException(status_code=404, detail="Task not found")

    del tasks[task_id]

prefix="/tasks" means every route on this router is automatically mounted under /tasks once it's registered — @router.get("/{task_id}") becomes /tasks/{task_id} in the running app without /tasks being repeated in every decorator. tags=["Tasks"] groups all of this router's routes under a single "Tasks" heading in Swagger UI.

The two collection-level routes are deliberately written as @router.post("") and @router.get("") rather than @router.post("/") and @router.get("/"). With a / in the path here, combined with the /tasks prefix, the actual registered path becomes /tasks/ with a trailing slash — and a request to /tasks without one gets redirected automatically with a 307 status rather than reaching the route directly. That redirect is often invisible in a browser, but it can break clients that don't follow redirects by default, or that don't resend the request body correctly on a 307. Using an empty string instead avoids the trailing slash entirely, so POST /tasks and GET /tasks are reached directly with no redirect involved.


Registering the Router​

main.py:


from fastapi import FastAPI

from routers import tasks



app = FastAPI()

app.include_router(tasks.router)

app.include_router(tasks.router) is what actually connects the router's routes to the running app — everything defined in routers/tasks.py becomes reachable only after this line runs, not the moment the router is created.


Confirming It Works​

With the server running, http://127.0.0.1:8000/docs shows all five task routes grouped under a "Tasks" section, matching the tags=["Tasks"] set on the router, with the same request/response schemas and "Try it out" testing available as they would be in a single-file app — moving the routes into their own file changes nothing about how they behave or how they're documented.


The Structure So Far​

Models live in models/, routes live in routers/, and main.py is reduced to creating the app and wiring routers into it — none of the actual endpoint logic lives there anymore. Adding a new resource later means adding a new model file and a new router file, then a single include_router call in main.py, rather than growing one file indefinitely.


Practice: Adding a Ping Router​

routers/ping.py:


from fastapi import APIRouter



router = APIRouter(prefix="/ping", tags=["Health"])



@router.get("")

def ping():

    return {"pong": True}

This follows the same shape as tasks.router — a router with its own prefix and tag, a route defined with an empty string to avoid the trailing-slash redirect covered earlier. Registering it in main.py:


from fastapi import FastAPI

from routers import tasks, ping



app = FastAPI()

app.include_router(tasks.router)

app.include_router(ping.router)

Visiting http://127.0.0.1:8000/docs now shows a new "Health" section alongside "Tasks," with a single GET /ping route listed under it, and calling it returns {"pong": true} — confirming the router was both defined and registered correctly.

Key Takeaways​

APIRouter lets routes be defined in their own file and mounted into the main app with a single include_router call, with prefix and tags controlling the URL structure and Swagger UI grouping respectively. Making that split actually work reliably depends on __init__.py files existing inside every folder being imported from as a package, not just at the project root. Registering collection-level routes with an empty string rather than "/" avoids a subtle trailing-slash redirect that's easy to miss in a browser but can trip up stricter HTTP clients — a small detail, but one that matters the moment a router's prefix and a route's own path combine to produce a URL ending in a slash.

Frequently Asked Questions​

Why do I get an ImportError like 'No module named models' when running main.py?

This almost always means an __init__.py file is missing from the models/ or routers/ folder, or the app isn't being run from inside the task_manager/ directory. Python needs both the __init__.py files present and the working directory set correctly for a plain import like from models.task import Task to resolve.

Why does my POST request to /tasks return a 307 redirect instead of creating a task?

This happens when a route is defined with @router.post("/") on a router that already has prefix="/tasks", producing a registered path of /tasks/ with a trailing slash. A request to /tasks without the slash gets redirected rather than reaching the route directly. Defining the route with an empty string, @router.post(""), avoids the trailing slash and the redirect entirely.

Why don't my task routes show up in Swagger UI at all?

The most common cause is forgetting to call app.include_router() in main.py. Creating an APIRouter and defining routes on it only makes those routes exist on the router object itself — they aren't connected to the running app, and won't appear in /docs, until include_router() is called with that router passed in.

Can a single router file define routes for more than one resource?

Yes, technically, but it works against the reason for modularizing in the first place. Keeping one router scoped to one resource (tasks, users, authentication) is what keeps each file readable and independently testable. If two resources are closely related, that's usually a sign they should each still get their own router, then be composed together in main.py.

Why does my in-memory tasks dictionary appear empty after restarting the server?

This is expected behavior, not a bug. The tasks dictionary lives only in the running process's memory, with nothing written to disk, so every restart starts from a clean, empty state. Persisting data across restarts requires an actual database in place of the dictionary.

Do prefix and tags need to match on an APIRouter?

No — they control two unrelated things. prefix determines the actual URL path every route on that router is mounted under, while tags only affects how routes are grouped and labeled in the generated documentation. A router can use any tag name regardless of what its prefix is.

Why does update_task() require every field, even when only one value is changing?

The route is defined with PUT, which conventionally replaces a resource in full — the updated_task: Task parameter requires every field Task declares as required, since a PUT request is expected to send the complete object, not a partial one. A route intended for partial updates should use PATCH with a model where every field is optional, or should read and modify only specific fields directly, rather than requiring a full Task body.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Intermediate API Design

Next

Database Integration