Router API

Complete API reference for the RouteMQ Router class and related components.

Router Class

The Router class is the core routing component that manages MQTT topic patterns and dispatches messages to appropriate handlers.

Constructor

from core.router import Router

router = Router()

Creates a new router instance with an empty route collection.

Methods

on(topic, handler, qos=0, middleware=None, shared=False, worker_count=1)

Register a route handler for a specific topic pattern.

Parameters:

  • topic (str): MQTT topic pattern with optional parameters (e.g., "devices/{device_id}/status")

  • handler (callable): Async function to handle matching messages

  • qos (int, optional): Quality of Service level (0, 1, or 2). Default: 0

  • middleware (List[Middleware], optional): Middleware to apply to this route. Default: None

  • shared (bool, optional): Enable shared subscription for load balancing. Default: False

  • worker_count (int, optional): Number of workers for shared subscriptions. Default: 1

Returns: None

Example:

group(prefix="", middleware=None)

Create a route group with shared prefix and middleware.

Parameters:

  • prefix (str, optional): Common topic prefix for all routes in the group. Default: ""

  • middleware (List[Middleware], optional): Middleware to apply to all routes in the group. Default: None

Returns: RouterGroup instance

Example:

dispatch(topic, payload, client)

Find a matching route and dispatch the message through middleware to the handler.

Parameters:

  • topic (str): The actual MQTT topic that received a message

  • payload (Any): Message payload (parsed JSON or raw bytes/string)

  • client: MQTT client instance

Returns: Any (the return value from the handler)

Raises: ValueError if no matching route is found

Example:

get_total_workers_needed()

Calculate the total number of workers needed for all shared routes.

Returns: int - Maximum worker count across all shared routes

Example:

Properties

routes

List of all registered Route objects.

Type: List[Route]

Example:

Route Class

Represents an individual route with its pattern, handler, and configuration.

Constructor

Note: Routes are typically created internally by Router.on(). Direct instantiation is rarely needed.

Properties

topic

The original topic pattern with parameters. Type: str Example: "devices/{device_id}/status"

handler

The async function that handles matching messages. Type: Callable

qos

Quality of Service level for this route. Type: int

middleware

List of middleware applied to this route. Type: List[Middleware]

shared

Whether this route uses shared subscriptions. Type: bool

worker_count

Number of workers for shared subscriptions. Type: int

pattern

Compiled regex pattern for topic matching. Type: re.Pattern

mqtt_topic

MQTT subscription topic with wildcards. Type: str Example: "devices/+/status" (for pattern "devices/{device_id}/status")

Methods

matches(topic)

Check if a topic matches this route and extract parameters.

Parameters:

  • topic (str): Actual MQTT topic

Returns: dict[str, str] | None - Extracted parameters or None if no match

Example:

get_subscription_topic(group_name=None)

Get the MQTT subscription topic, with shared prefix if needed.

Parameters:

  • group_name (str, optional): Group name for shared subscriptions

Returns: str - MQTT subscription topic

Example:

RouterGroup Class

Context manager for grouping routes with shared prefixes and middleware.

Constructor

Note: RouterGroup instances are created by Router.group(). Direct instantiation is not recommended.

Methods

on(topic, handler, qos=0, middleware=None, shared=False, worker_count=1)

Register a route handler within this group.

Parameters: Same as Router.on(), but topic is relative to the group's prefix

Example:

Properties

router

Reference to the parent Router instance. Type: Router

prefix

Topic prefix for this group. Type: str

middleware

Middleware applied to all routes in this group. Type: List[Middleware]

Topic Pattern Syntax

RouteMQ uses Laravel-style route parameters in topic patterns:

Parameter Syntax

  • {parameter_name} - Captures a single topic level

  • Parameters can contain letters, numbers, underscores, and hyphens

  • Parameters cannot contain forward slashes

Examples

MQTT Wildcard Conversion

Route parameters are automatically converted to MQTT wildcards:

Error Handling

Common Exceptions

ValueError

Raised by dispatch() when no route matches the topic.

Best Practices

  1. Route Order: Routes are matched in registration order. More specific routes should be registered first.

  2. Parameter Validation: Validate parameters in your handlers:

  1. Middleware Usage: Use middleware for cross-cutting concerns:

  1. Shared Subscriptions: Use for high-throughput scenarios:

Complete Example

Last updated