Routers and Sub-Applications
Nexios provides a powerful routing system that allows you to create modular and nested routing structures. Here's an example of how you can use routers and sub-applications in your application
🆕 Creating a Router and Mounting it to the Main Application
from nexios import NexiosApp
from nexios.routing import Router
app = NexiosApp()
v1_router = Router(prefix="/v1")
@v1_router.get("/users")
async def list_users(req, res):
return res.json({"message": "List of users"})
@v1_router.get("/users/{user_id}")
async def get_user(req, res, user_id):
return res.json({"user_id": user_id})
app.mount_router(v1_router)
Overriding Prefix at Mount Time You can override the default router prefix when mounting it to the app. This is helpful when reusing a router module in multiple places.
app.mount_router(v1_router, prefix="/api/v1")
Tip 💡
he prefix in mount_router always takes precedence over the one set in the Router instance.
This example creates a router with two routes, one for listing users and another for getting a specific user. The router is then mounted to the main application using the mount_router
method.
This matches /v1/users
and /v1/users/{user_id}
⚠️ Bug Alert
Ensure to use mount_router
after all routes have been defined.
🤷♂️ What is Router?
A Router is a container for routes and sub-applications. It allows you to create a modular and nested routing structure in your application.
⚠️ Bug Alert
Ensure all mounted sub application or sub-routers have unique prefixes
Routers can contain other routers. This is useful when you want even finer modularization, e.g., versioned APIs with internal domains.
app = NexiosApp()
v1_router = Router(prefix="/v1")
user_router = Router(prefix="/users")
@user_router.get("/")
async def index(req, res):
return res.text("User root")
@user_router.get("/{id}")
async def detail(req, res, id):
return res.json({"user": id})
# Mount user_router inside v1_router
v1_router.mount_router(user_router)
# Mount v1_router into the app
app.mount_router(v1_router)
Now, the final paths are:
/v1/users/
/v1/users/{id}
You can nest as deeply as you want. Internally, Nexios flattens the route tree during app startup for performance.
The Router
class also have similar routing methods as NexiosApp
class
🌴 Sub-Applications = Routers
NexiosApp is a subclass of Router. This means you can treat entire apps as routers and mount them.
main_app = NexiosApp()
admin_app = NexiosApp()
@admin_app.get("/dashboard")
async def dashboard(req, res):
return res.text("Welcome to the admin panel")
main_app.mount_router(admin_app, prefix="/admin")
Now you can access /admin/dashboard.
This makes it trivial to build modular applications where teams can work on separate parts (e.g., auth, billing, analytics) in isolation and plug them into a larger system