Instance-scoped routing engine for Python with hierarchical handlers and composable plugins
Project description
Genro Routes
Genro Routes is a transport-agnostic routing engine that decouples method routing from how those methods are exposed. Define your handlers once, then expose them via HTTP, CLI, WebSocket, or any other transport layer.
The routing logic lives in your application objects - the transport adapter (like genro-asgi for HTTP) simply maps external requests to router entries.
Why Transport-Agnostic?
Traditional web frameworks tightly couple routing to HTTP. Genro Routes separates these concerns:
| Layer | Responsibility |
|---|---|
| genro-routes | Method registration, hierarchies, plugins, introspection |
| Transport adapter | Protocol handling, request/response mapping |
This separation enables:
- Same handlers, multiple transports - Expose your API via HTTP and CLI without duplication
- Runtime introspection - Query available routes, generate documentation, build admin UIs
- Testability - Test business logic without HTTP overhead
- Flexibility - Swap transports without changing application code
Use Cases
- HTTP APIs - Via genro-asgi adapter
- CLI tools - Via the built-in
RoutingCliadapter (see below) - Internal services - Direct method invocation with plugin pipeline
- Admin dashboards - Runtime introspection for dynamic UIs
Key Features
- Instance-scoped routers - Each object instantiates its own routers (
Router(self, ...)) with isolated state. - Friendly registration -
@route(...)accepts explicit names, auto-strips prefixes, and supports custom metadata. - Simple hierarchies -
attach_instance(child, name="alias")(method onRoutingClass) connects instances with path access (parent.api.node("child/method")). - Plugin pipeline -
BasePluginprovideson_decore/wrap_handlerhooks and plugins inherit from parents automatically. - Runtime configuration -
routing.configure()applies global or per-handler overrides with wildcards and returns reports ("?"). - Built-in plugins -
logging,pydantic,auth,env,openapi, andchannelplugins are included out of the box. - Response schema generation - Return type annotations (TypedDict, dataclass, etc.) are automatically converted to JSON Schema and exposed in route metadata for bridges to consume.
- Full coverage - The package ships with a comprehensive test suite and no hidden compatibility layers.
Quick Example
from genro_routes import RoutingClass, Router, route
class OrdersAPI(RoutingClass):
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.node("list")()) # ["order-1", "order-2"]
print(orders.api.node("retrieve")("42")) # acme:42
overview = orders.api.nodes()
print(overview["entries"].keys()) # dict_keys(['list', 'retrieve', 'create'])
Hierarchical Routing
Build nested service structures with path access:
class UsersAPI(RoutingClass):
def __init__(self):
self.api = Router(self, name="api")
@route("api")
def list(self):
return ["alice", "bob"]
class Application(RoutingClass):
def __init__(self):
self.api = Router(self, name="api")
self.users = UsersAPI()
# Attach child service
self.attach_instance(self.users, name="users")
app = Application()
print(app.api.node("users/list")()) # ["alice", "bob"]
# Introspect hierarchy
info = app.api.nodes()
print(info["routers"].keys()) # dict_keys(['users'])
Learn by Example
We provide a comprehensive gallery of examples in the examples/ directory:
- Standard Faker - Explicit routing and Pydantic validation.
- Magic Faker - Dynamic mapping of library methods at runtime.
- Syntax Highlighting - Creating a service wrapper around the Pygments library.
- Auth & Roles - Implementing role-based access control.
- Service Composition - Building complex apps from independent modules.
Read our guide on Why wrap a library with Genro-Routes? for more specialized insights.
CLI Adapter
Expose any RoutingClass as a full-featured command-line tool with tab completion, help, and typed parameters — automatically generated from router introspection.
pip install genro-routes[cli]
#!/usr/bin/env python
from genro_routes.cli import RoutingCli
from myapp import OrdersAPI
cli = RoutingCli(OrdersAPI("acme"))
cli.run()
$ myapp list # call handler directly
["order-1", "order-2"]
$ myapp retrieve 42 # positional arguments
acme:42
$ myapp --help # auto-generated help
Usage: myapp [OPTIONS] COMMAND [ARGS]...
Commands:
create Create a new order.
list List all orders.
retrieve Retrieve a single order.
$ myapp retrieve --help # per-command help with types
Usage: myapp retrieve [OPTIONS] IDENT
Arguments:
IDENT (str)
Features:
- Routers become command groups - Multiple routers create nested subcommands
- Parameters from signatures - Type hints map to click types (int, bool flags, Choice for Literal/Enum, multiple for list)
- Tab completion - Native bash/zsh/fish via click (
eval "$(_MYAPP_COMPLETE=bash_source myapp)") - Output formatting - Auto (JSON for dicts, plain for strings), or force
json/table/raw - Accepts class or instance -
RoutingCli(MyClass)orRoutingCli(MyClass(config=cfg))
Installation
pip install genro-routes
With CLI support:
pip install genro-routes[cli]
For development:
git clone https://github.com/genropy/genro-routes.git
cd genro-routes
pip install -e ".[all]"
Typed Response Schemas
Annotate return types to generate response schemas automatically. Bridges (MCP, OpenAPI) can expose them without extra work:
from typing import TypedDict
from genro_routes import RoutingClass, Router, route
class UserResponse(TypedDict):
id: int
name: str
active: bool
class UsersAPI(RoutingClass):
def __init__(self):
self.api = Router(self, name="api").plug("pydantic")
@route("api")
def get_user(self, user_id: int) -> UserResponse:
return {"id": user_id, "name": "alice", "active": True}
api = UsersAPI()
# Response schema is available in route metadata
entry = api.api._entries["get_user"]
schema = entry.metadata["pydantic"]["response_schema"]
# {"type": "object", "properties": {"id": {"type": "integer"}, ...}}
# OpenAPI translation includes it automatically
openapi = api.api.nodes(mode="openapi")
# paths["/get_user"]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
Supported types: TypedDict, dict[str, int], list[...], str, int, bool, and any type Pydantic can serialize.
Core Concepts
Router- Runtime router bound directly to an object viaRouter(self, name="api")@route("name")- Decorator that marks bound methods for the router with the matching nameRoutingClass- Mixin that tracks routers per instance and exposes theroutingproxyRoutingContext- Extensible execution context with parent chain delegation. Attach any attribute (ctx.db,ctx.user,ctx.session); missing lookups walk upRoutingContext(parent=...). Stored in a_ctxslot on each instance — children inherit via_routing_parentchain. See Execution Context Guide.BasePlugin- Base class for creating plugins withon_decoreandwrap_handlerhooksobj.routing- Proxy exposed by every RoutingClass that provides helpers likeget_router(...)andconfigure(...)for managing routers/plugins without polluting the instance namespace.RouterNode- Callable wrapper returned bynode(), withpath,error,doc,metadataproperties.NotFound/NotAuthenticated/NotAuthorized/NotAvailable- Exceptions for routing errors (not found, auth required, auth denied, capabilities missing)
One Name Per Operation
Genro Routes uses unique names for handlers rather than overloading the same path with different HTTP methods. Each entry is an operation (list_orders, create_order, approve_order), not a resource acted upon by a verb.
This matches how modern API paradigms work: GraphQL, gRPC, tRPC, and MCP all identify operations by name, not by HTTP method. The HTTP verb is inferred automatically at the transport layer (e.g., genro-asgi) when generating OpenAPI schemas or mapping to HTTP endpoints.
See Why One Name Per Operation for the full rationale.
Pattern Highlights
- Explicit naming + prefixes -
@route("api", name="detail")andRouter(self, prefix="handle_")separate method names from public route names. - Explicit instance hierarchies -
self.attach_instance(child, name="alias")connects RoutingClass instances. Retrieve children later withrouting.instance("api/alias"). - Endpoint ID -
@route("api", endpoint_id="USR-001")assigns a stable identifier for reverse lookup viarouter.node("@USR-001"). - Branch routers -
Router(self, branch=True)creates pure organizational nodes without handlers. - Built-in and custom plugins -
Router(self, ...).plug("logging"),Router(self, ...).plug("pydantic"), or custom plugins. - Shorthand plugin syntax -
@route("api", auth="admin")instead of@route("api", auth_rule="admin"). Plugins declare their default parameter viaplugin_default_param. - Channel filtering -
@route("api", channel="mcp,bot_.*")controls which transport channels can access each handler. Supports regex patterns. - Runtime configuration -
routing.configure("api:logging/_all_", enabled=False)applies targeted overrides with wildcards or batch updates. - Lazy binding - Routers auto-bind on first use; no explicit
bind()call needed.
Documentation
- Full Documentation - Complete guides, tutorials, and API reference
- Quick Start - Get started in 5 minutes
- Execution Context - RoutingContext, parent chain, slot-based ctx
- FAQ - Common questions and answers
Testing
Genro Routes ships with a comprehensive test suite:
PYTHONPATH=src pytest --cov=src/genro_routes --cov-report=term-missing
All examples in documentation are verified by the test suite.
Repository Structure
genro-routes/
├── src/genro_routes/
│ ├── __init__.py # Public API exports
│ ├── exceptions.py # NotFound, NotAuthorized, NotAuthenticated, NotAvailable
│ ├── core/ # Core router implementation
│ │ ├── base_router.py # BaseRouter (plugin-free runtime)
│ │ ├── router.py # Router (with plugin support)
│ │ ├── router_node.py # RouterNode (callable wrapper from node())
│ │ ├── router_interface.py # RouterInterface (abstract base)
│ │ ├── context.py # RoutingContext (extensible execution context)
│ │ ├── decorators.py # @route decorator
│ │ └── routing.py # RoutingClass, ResultWrapper
│ ├── cli/ # CLI transport adapter
│ │ ├── __init__.py # RoutingCli (public API)
│ │ ├── _builder.py # CliBuilder (click tree from nodes())
│ │ ├── _type_map.py # ParamConverter (Python → click types)
│ │ └── _formatters.py # OutputFormatter (JSON/table/raw)
│ └── plugins/ # Built-in plugins
│ ├── _base_plugin.py # BasePlugin, MethodEntry
│ ├── logging.py # LoggingPlugin
│ ├── pydantic.py # PydanticPlugin
│ ├── auth.py # AuthPlugin
│ ├── env.py # EnvPlugin (+ CapabilitiesSet)
│ ├── openapi.py # OpenAPIPlugin (+ OpenAPITranslator)
│ └── channel.py # ChannelPlugin (channel-based filtering)
├── examples/ # Example applications
├── tests/ # Comprehensive test suite
└── docs/ # Documentation (Sphinx)
Project Status
Genro Routes is currently in beta. The core API is stable with complete documentation.
- Python Support: 3.10, 3.11, 3.12, 3.13
- License: Apache 2.0
Current Limitations
- Instance methods only - Routers assume decorated functions are bound methods (no static/class method or free function support)
- Minimal plugin system - Intentionally simple; advanced features must be added manually
Roadmap
- genro-asgi - ASGI adapter for HTTP exposure (in development)
- Additional plugins (async, storage, audit trail, metrics)
- Example applications and use cases
Contributing
Contributions are welcome! Please see CONTRIBUTING.md for guidelines.
License
Apache License 2.0 - see LICENSE for details.
Origin
This project was originally developed as "smartroute" under MIT license and has been renamed and relicensed.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file genro_routes-0.22.0.tar.gz.
File metadata
- Download URL: genro_routes-0.22.0.tar.gz
- Upload date:
- Size: 2.9 MB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f83b1ef42989db7e2581ac6b97a53985300cfe455a754f08313e5a3185872ca
|
|
| MD5 |
56af05c52c04912cbfb12b0b5e7f9c7a
|
|
| BLAKE2b-256 |
a621609eb969fa237970b9c3c4efda6c047df71a534550bfd5256f1cad5ebda3
|
Provenance
The following attestation bundles were made for genro_routes-0.22.0.tar.gz:
Publisher:
publish.yml on genropy/genro-routes
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
genro_routes-0.22.0.tar.gz -
Subject digest:
3f83b1ef42989db7e2581ac6b97a53985300cfe455a754f08313e5a3185872ca - Sigstore transparency entry: 1252831327
- Sigstore integration time:
-
Permalink:
genropy/genro-routes@70a7d6c63fa639ec3a87b1ed80f86b591da0eef9 -
Branch / Tag:
refs/tags/v0.22.0 - Owner: https://github.com/genropy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@70a7d6c63fa639ec3a87b1ed80f86b591da0eef9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file genro_routes-0.22.0-py3-none-any.whl.
File metadata
- Download URL: genro_routes-0.22.0-py3-none-any.whl
- Upload date:
- Size: 73.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6eb486cb6d457b390ebec2e31506bedda249b2df00b48b54c4732701c2532ea2
|
|
| MD5 |
6268c0456b316825575ed0f0dddba6b8
|
|
| BLAKE2b-256 |
38aa7cedc9e6abd24ad18d2b2326f1c20364c24605633ca66f44f47e177359c9
|
Provenance
The following attestation bundles were made for genro_routes-0.22.0-py3-none-any.whl:
Publisher:
publish.yml on genropy/genro-routes
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
genro_routes-0.22.0-py3-none-any.whl -
Subject digest:
6eb486cb6d457b390ebec2e31506bedda249b2df00b48b54c4732701c2532ea2 - Sigstore transparency entry: 1252831436
- Sigstore integration time:
-
Permalink:
genropy/genro-routes@70a7d6c63fa639ec3a87b1ed80f86b591da0eef9 -
Branch / Tag:
refs/tags/v0.22.0 - Owner: https://github.com/genropy
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@70a7d6c63fa639ec3a87b1ed80f86b591da0eef9 -
Trigger Event:
push
-
Statement type: