Skip to main content

Instance-scoped routing engine for Python with hierarchical handlers and composable plugins

Project description

SmartRoute

SmartRoute Logo

PyPI version Tests codecov Documentation Python 3.10+ License: MIT Code style: black

SmartRoute is a fully runtime routing engine that lets you expose Python methods as "endpoints" (CLI tools, orchestrators, internal services) without global blueprints or shared registries. Each instance creates its own routers, can attach child routers, configure plugins, and provides ready-to-use runtime introspection.

Use SmartRoute when you need to:

  • Compose internal services with many handlers (application APIs, orchestrators, CLI automation)
  • Build dashboards/portals that register routers dynamically and need runtime introspection
  • Extend handler behavior with plugins (logging, validation, audit trails)

SmartRoute provides a consistent, well-tested foundation for these patterns.

Key Features

  1. Instance-scoped routers – Each object instantiates its own routers (Router(self, ...)) with isolated state.
  2. Friendly registration@route(...) accepts explicit names, auto-strips prefixes, and supports custom metadata.
  3. Simple hierarchiesadd_child("child1, child2") connects child routers with dotted path access (parent.api.get("child.method")).
  4. Plugin pipelineBasePlugin provides on_decore/wrap_handler hooks and plugins inherit from parents automatically.
  5. Runtime configurationroutedclass.configure() applies global or per-handler overrides with wildcards and returns reports ("?").
  6. Optional extraslogging, pydantic, scope plugins and SmartAsync wrapping are opt-in; the core has minimal dependencies.
  7. Full coverage – The package is 99% test coverage with 74 comprehensive tests with no hidden compatibility layers.

Standard channel codes

ScopePlugin uses uppercase channel codes to mark where routes may be exposed. Built-in conventions:

  • CLI – Publisher CLI commands
  • SYS_HTTP / SYS_WS – shared Publisher HTTP/WebSocket servers
  • HTTP / WS – per-app FastAPI/WS endpoints
  • MCP – Machine Control Protocol adapters (AI integrations)

Additional channels can be declared per router (still uppercase strings) without touching the core.

from smartroute import channels

print(channels["CLI"])  # -> "Publisher CLI commands"

Quick Example

from smartroute import RoutedClass, Router, route

class OrdersAPI(RoutedClass):
    def __init__(self, label: str):
        self.label = label
        self.api = Router(self, name="orders")

    @route("orders")
    def list(self):
        return ["order-1", "order-2"]

    @route("orders")
    def retrieve(self, ident: str):
        return f"{self.label}:{ident}"

    @route("orders")
    def create(self, payload: dict):
        return {"status": "created", **payload}

orders = OrdersAPI("acme")
print(orders.api.get("list")())        # ["order-1", "order-2"]
print(orders.api.get("retrieve")("42"))  # acme:42

overview = orders.api.members()
print(overview["handlers"].keys())      # dict_keys(['list', 'retrieve', 'create'])
# Filter only handlers exposing a given scope
internal_only = orders.api.members(scopes="internal")
# Or limit both scope and channel
internal_cli = orders.api.members(scopes="internal", channel="CLI")

Installation

pip install smartroute

For development:

git clone https://github.com/genropy/smartroute.git
cd smartroute
pip install -e ".[all]"

To use the Pydantic plugin:

pip install smartroute[pydantic]

Core Concepts

  • Router – Runtime router bound directly to an object via Router(self, name=\"api\")
  • @route(\"name\") – Decorator that marks bound methods for the router with the matching name
  • RoutedClass – Mixin that tracks routers per instance and exposes the routedclass proxy
  • BasePlugin – Base class for creating plugins with on_decore and wrap_handler hooks
  • obj.routedclass – Proxy exposed by every RoutedClass that provides helpers like get_router(...) and configure(...) for managing routers/plugins without polluting the instance namespace.

Pattern Highlights

  • Explicit naming + prefixes@route("api", name="detail") and Router(prefix="handle_") separate method names from public route names (test_prefix_and_name_override).
  • Attribute-level hierarchiesself.api.add_child("sales, finance") connects child routers by discovering them from instance attributes (test_dashboard_hierarchy).
  • Bulk registration – Dictionaries or iterables allow connecting routers from external structures (test_add_child_accepts_mapping_for_named_children).
  • Built-in and custom pluginsRouter(...).plug("logging"), Router(...).plug("pydantic"), Router(...).plug("scope") or custom plugins (llm-docs/PATTERNS.md#pattern-12-custom-plugin-development).
  • Runtime configurationroutedclass.configure("api:logging/foo", enabled=False) applies targeted overrides with wildcards or batch updates (see dedicated guide).
  • Dynamic registrationrouter.add_entry(handler) or router.add_entry("*") allow publishing handlers computed at runtime (tests/test_router_runtime_extras.py).

Documentation

  • Full Documentation – Complete guides, tutorials, and API reference
  • Quick Start – Get started in 5 minutes
  • FAQ – Common questions and answers about SmartRoute and plugins
  • LLM Reference – Token-optimized reference for AI code generation
  • API Details – Complete API reference generated from tests
  • Usage Patterns – Common patterns extracted from test suite

Testing

SmartRoute achieves 99% test coverage with 74 comprehensive tests:

PYTHONPATH=src pytest --cov=src/smartroute --cov-report=term-missing

All examples in documentation are verified by the test suite and linked with test anchors.

Repository Structure

smartroute/
├── src/smartroute/
│   ├── core/               # Core router implementation
│   │   ├── router.py       # Router runtime implementation
│   │   ├── decorators.py   # @route and @routers decorators
│   │   └── base.py         # BasePlugin and MethodEntry
│   └── plugins/            # Built-in plugins
│       ├── logging.py      # LoggingPlugin
│       ├── pydantic.py     # PydanticPlugin
│       └── scope.py        # ScopePlugin
├── tests/                  # Test suite (>95% coverage)
│   ├── test_switcher_basic.py        # Core functionality
│   ├── test_router_edge_cases.py     # Edge cases
│   ├── test_plugins_new.py           # Plugin system
│   └── test_pydantic_plugin.py       # Pydantic validation
├── docs/                   # Human documentation (Sphinx)
├── llm-docs/              # LLM-optimized documentation
└── examples/              # Example implementations

Project Status

SmartRoute is currently in beta (v0.5.0). The core API is stable with complete documentation.

  • Test Coverage: 99% (74 tests, 1042 statements)
  • Python Support: 3.10, 3.11, 3.12
  • License: MIT

Current Limitations

  • Instance methods only – Routers assume decorated functions are bound methods (no static/class method or free function support)
  • No SmartAsync pluginget(..., use_smartasync=True) is optional but there's no dedicated SmartAsync plugin
  • Minimal plugin system – Intentionally simple; advanced features (e.g., Pydantic declarative config) must be added manually

Roadmap

  • ✅ Complete Sphinx documentation with tutorials and API reference
  • Additional plugins (async, storage, audit trail, metrics)
  • Benchmarks and performance comparison
  • Example applications and use cases

Contributing

Contributions are welcome! Please see CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE for details.

Acknowledgments

SmartRoute was designed with lessons learned from real-world production use.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smartroute-0.5.1.tar.gz (45.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smartroute-0.5.1-py3-none-any.whl (37.3 kB view details)

Uploaded Python 3

File details

Details for the file smartroute-0.5.1.tar.gz.

File metadata

  • Download URL: smartroute-0.5.1.tar.gz
  • Upload date:
  • Size: 45.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for smartroute-0.5.1.tar.gz
Algorithm Hash digest
SHA256 04d98beac7efb03d9f1b67400aabc428302338cb91aadcdca592a947a79dad65
MD5 378ad486050a5a591df282fc7bf7ee14
BLAKE2b-256 e04959a1c5aa314f810854b5c71475803d227cefb4ba7e7852b91e5eb2b916d8

See more details on using hashes here.

Provenance

The following attestation bundles were made for smartroute-0.5.1.tar.gz:

Publisher: publish.yml on genropy/smartroute

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file smartroute-0.5.1-py3-none-any.whl.

File metadata

  • Download URL: smartroute-0.5.1-py3-none-any.whl
  • Upload date:
  • Size: 37.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for smartroute-0.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 1a12fc4728d601ea836dbcaad57728abddb0822e511412836b556007e65284e3
MD5 b5bcf5952c85fa1915a51c09a210ae1b
BLAKE2b-256 04535d04843a966df8b102db0023360e70d37e23301b91bfe8dc496f0b9d31ce

See more details on using hashes here.

Provenance

The following attestation bundles were made for smartroute-0.5.1-py3-none-any.whl:

Publisher: publish.yml on genropy/smartroute

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page