Python FastAPI Tutorial (Part 8): Routers - Organizing Routes into Modules with APIRouter
TL;DR
This tutorial demonstrates how to refactor a monolithic FastAPI application by using APIRouter to organize routes into separate modules, keeping main.py clean while maintaining identical external URLs and functionality.
🗂️ Router Fundamentals 2 insights
APIRouter acts as modular blueprints
APIRouter allows grouping related routes into separate Python files similar to Flask blueprints, enabling better code organization before adding complex features like authentication.
Directory structure follows resource pattern
Create a routers/ package with __init__.py and separate files for each resource (users.py, post.py) to isolate database models, schemas, and endpoint logic.
⚙️ Implementation Strategy 3 insights
Use relative paths with prefixes
Define routes in router files using empty strings or relative paths, then apply the full prefix (e.g., "/api/users") when including the router in main.py to avoid trailing slash issues.
Replace app decorators with router
Change @app.get/post decorators to @router.get/post and move all associated imports and logic into the dedicated router file, keeping only template routes in main.py.
Tag routes for documentation grouping
Include tags=["users"] parameter when registering routers to automatically organize endpoints into collapsible sections in the auto-generated /docs interface.
✅ Architecture Benefits 3 insights
Eliminate monolithic main.py
Refactoring reduces main.py from hundreds of mixed lines to under 150 lines containing only app configuration, template views, and router imports.
Enable team scalability
Separation of concerns allows multiple developers to work on different routers simultaneously with fewer merge conflicts and enables individual router testing.
Avoid function name collisions
Use unique descriptive function names across routers to prevent conflicts with template route names, as FastAPI uses function names for internal route identification.
Bottom Line
Organize FastAPI applications by creating separate router modules for each resource using APIRouter, applying URL prefixes and tags in main.py to maintain clean separation of concerns while keeping external API contracts unchanged.
More from Corey Schafer
View all
Python FastAPI Tutorial (Part 13): Pagination - Loading More Data with Query Parameters
This tutorial demonstrates how to implement offset-based pagination in FastAPI using skip and limit query parameters, covering backend schema design with SQLAlchemy queries and frontend integration with a 'load more' button pattern.
Python FastAPI Tutorial (Part 12): File Uploads - Image Processing, Validation, and Storage
Corey Schafer demonstrates implementing secure profile picture uploads in FastAPI using Pillow for image resizing and format standardization, with proper handling of CPU-bound tasks in async contexts and safe file transaction patterns to prevent data loss.
Python FastAPI Tutorial (Part 11): Authorization - Protecting Routes and Verifying Current User
This tutorial demonstrates how to implement proper authorization in FastAPI by creating a reusable dependency that validates JWT tokens and retrieves the current user, enabling secure route protection and ownership verification while eliminating hard-coded user IDs.
Python FastAPI Tutorial (Part 10): Authentication - Registration and Login with JWT
This tutorial establishes backend authentication infrastructure for FastAPI by implementing Argon2 password hashing, JWT token management, and Pydantic Settings configuration, while updating database models and schemas to support secure user registration and login workflows.