Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Organizing FastAPI Applications with APIRouter for Modular Routing

Notes May 13 1

As FastAPI applications grow in complexity, consolidating all routes within a single file becomes cumbersome and difficult to maintain. Route distribution enables developers to seperate functionality into distinct modules, enhancing code organization and scalability. For instance, an e-commerce system might isolate user management, order procesing, and product catalog into independent modules.

FastAPI's APIRouter facilitates this by allowing the creation of sub-routes that can be integrated into the main application. The process involves two primary steps: constructing sub-routes with APIRouter and incorporating them into the primary app using include_router().

Consider a project structure where modules are housed in a dedicated directory:

├── main.py
└── modules/
    ├── users/
    │   └── endpoints.py
    └── orders/
        └── endpoints.py

In the users module, define routes within endpoints.py:

# modules/users/endpoints.py
from fastapi import APIRouter

user_router = APIRouter()

@user_router.get("/profile")
def fetch_user_profile():
    return {"message": "User profile data"}

Similarly, for the orders module:

# modules/orders/endpoints.py
from fastapi import APIRouter

order_router = APIRouter()

@order_router.get("/all")
def retrieve_orders():
    return {"message": "List of orders"}

@order_router.get("/{order_id}")
def fetch_order_details(order_id: int):
    return {"message": f"Details for order ID: {order_id}"}

In the main application file, import and include these routers:

# main.py
from fastapi import FastAPI
from modules.users.endpoints import user_router
from modules.orders.endpoints import order_router

app = FastAPI()

app.include_router(user_router, prefix="/users", tags=["User Operations"])
app.include_router(order_router, prefix="/orders", tags=["Order Management"])

The include_router method attaches the sub-routes to the main app, with prefix prepending a path segment to all routes in that router and tags grouping endpoints in the auto-generated documentation.

Launch the application with a command like uvicorn main:app --reload and navigate to http://127.0.0.1:8000/docs. The interactive documentation will display the routes under their respective tags, with paths such as /users/profile and /orders/all. Accessing /orders/5 would invoke the detail endpoint with order_id set to 5.

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.