Examples¶
Every snippet below comes from a runnable Python file in docs/examples/ and is tested in CI.
Quickstart App¶
Define an app with path parameters and msgspec.Struct responses:
docs/examples/quickstart_app.py
class HealthStatus(msgspec.Struct):
"""Health check payload returned by the quickstart application."""
status: str
service: str
def create_app() -> App:
"""Create and configure the quickstart Vertebra application."""
app = App()
@app.get("/health")
def health() -> HealthStatus:
return HealthStatus(status="ok", service="vertebra")
@app.get("/users/{user_id:int}")
def get_user(user_id: int) -> dict[str, int | str]:
return {"id": user_id, "role": "admin"}
app.enable_docs()
return app
def main() -> None:
"""Verify route indexing, typed path extraction, and OpenAPI generation."""
app = create_app()
health_id = handler_id("GET", "/health")
assert health_id in app.handler_index
assert app.handler_index[health_id].path == "/health"
params = extract_path_params("/users/{user_id:int}", "/users/42")
assert params == {"user_id": 42}
Controllers, Routers & Dependency Injection¶
Group routes on a controller with injected dependencies and typed request models:
docs/examples/routing_and_dtos.py
class CreateItemRequest(msgspec.Struct):
"""Incoming payload for creating an inventory item."""
sku: str
quantity: int
class ItemResponse(msgspec.Struct):
"""Serialized inventory item returned to callers."""
id: int
sku: str
quantity: int
class InventoryService:
"""Domain service injected into controllers and routes."""
def fetch(self, item_id: int) -> ItemResponse:
"""Fetch an item by identifier."""
return ItemResponse(id=item_id, sku="VTB-100", quantity=5)
class ItemController(Controller):
"""Controller grouping item routes under a shared path and dependencies."""
path = "/items"
dependencies = {"service": Provide(InventoryService, scope="singleton")}
@post("/", status_code=201)
def create_item(self, body: CreateItemRequest) -> ItemResponse:
"""Create a new item from a typed msgspec payload."""
return ItemResponse(id=1, sku=body.sku, quantity=body.quantity)
@get("/{item_id:int}")
def get_item(self, item_id: int, service: InventoryService) -> ItemResponse:
"""Return an item using the injected InventoryService."""
return service.fetch(item_id)
def build_items_router() -> Router:
"""Build a modular router mounting ItemController under /api/v1."""
return Router(prefix="/api/v1", route_handlers=[ItemController])
def build_procedures() -> ProcedureRouter:
"""Build a typed RPC router with query and mutation procedures."""
rpc = ProcedureRouter(prefix="/_rpc")
@rpc.mutation(input_type=CreateItemRequest, output_type=ItemResponse)
async def reserve_item(payload: CreateItemRequest) -> ItemResponse:
return ItemResponse(id=9, sku=payload.sku, quantity=payload.quantity)
return rpc
def main() -> None:
"""Mount the items router on an App and invoke the typed RPC procedure."""
app = App(route_handlers=[build_items_router()])
assert len(app.routes) == 2
rpc = build_procedures()
req = CreateItemRequest(sku="VTB-001", quantity=12)
result = asyncio.run(rpc.call("reserve_item", req))
assert result == ItemResponse(id=9, sku="VTB-001", quantity=12)
Background Queues¶
Enqueue, lease, and acknowledge jobs with an in-memory queue backend:
docs/examples/background_queues.py
async def send_welcome_email(user_id: int) -> dict[str, int | str]:
"""Deliver a welcome email for the given user_id."""
return {"user_id": user_id, "status": "sent"}
async def run_queue_workflow() -> None:
"""Register a TaskDef, enqueue an envelope, and drain the in-memory queue."""
service = QueueService(QueueConfig(backend_url="memory://"))
service.register(TaskDef(name="send_welcome_email", fn=send_welcome_email, lane="io"))
envelope = await service.enqueue("send_welcome_email", 42)
assert envelope.task_name == "send_welcome_email"
assert envelope.lane == "io"
outcomes = await service.drain_once(lanes=("io",))
assert outcomes == [{"user_id": 42, "status": "sent"}]
cron = CronExpression.parse("*/15 * * * *")
assert 0 in cron.minutes
assert 15 in cron.minutes
await service.close()
def main() -> None:
"""Execute the async background queue workflow."""
asyncio.run(run_queue_workflow())
Live State & Inertia¶
Run actions on a live state component and build an Inertia response:
docs/examples/live_state_and_ssr.py
class CounterLive(LiveState):
"""Server-owned reactive counter component with LWW delta synchronization."""
count: int = 0
step: int = 1
@live_action
async def increment(self) -> int:
"""Increment the counter by the configured step."""
self.count += self.step
return self.count
async def run_live_and_inertia_demo() -> None:
"""Mutate a LiveState component, broadcast deltas, and build an Inertia page."""
state = CounterLive(count=0, step=2)
room = LiveStateRoom("counter:room", state)
await state.increment()
assert state.count == 2
frames = await room.broadcast_pending()
assert len(frames) == 1
snap = state.snapshot()
assert snap["count"] == 2 and snap["step"] == 2
middleware = SyncInertiaMiddleware(InertiaConfig(enabled=True, version="1.0.0"))
response = inertia("Dashboard/Overview", {"count": state.count})
class DummyRequest:
method = "GET"
path = "/dashboard"
headers: dict[str, str] = {"X-Inertia": "true"}
page = middleware.build_page_object(DummyRequest(), response)
assert page["component"] == "Dashboard/Overview"
assert page["props"]["count"] == 2
def main() -> None:
"""Execute the LiveState and Inertia verification workflow."""
asyncio.run(run_live_and_inertia_demo())
Object Storage & SQLite¶
Save model file attachments and run SQLite transactions with object storage:
docs/examples/storage_and_db.py
def main() -> None:
"""Save model file attachments and execute transactional SQLite queries."""
store = SyncObjectStore("memory://")
backend = ObjectStoreBackend(store=store, prefix="reports")
file_obj = FileObject(backend=backend, filename="q1.json")
saved = backend.save_object(file_obj, b'{"quarter": "Q1"}')
assert saved.size == 17
assert backend.get_content("q1.json") == b'{"quarter": "Q1"}'
registry = DatabaseRegistry()
db = provide_driver(SQLiteConfig(path=":memory:"), sync=True, registry=registry)
try:
db.execute("CREATE TABLE reports (id INTEGER PRIMARY KEY, key TEXT NOT NULL)")
file_obj2 = FileObject(backend=backend, filename="q2.json")
backend.save_object(file_obj2, b'{"quarter": "Q2"}')
with db.transaction():
inserted = db.execute("INSERT INTO reports (key) VALUES (?)", ("reports/q2.json",))
assert inserted == 1
row = db.select_one("SELECT key FROM reports WHERE id = ?", (1,))
assert row == {"key": "reports/q2.json"}
assert db.select_one_or_none("SELECT key FROM reports WHERE id = ?", (99,)) is None
with db.select_to_arrow("SELECT id, key FROM reports") as cursor:
assert cursor.row_count == 1
try:
db.select_one("SELECT key FROM reports WHERE id = ?", (99,))
except NotFoundError as exc:
assert isinstance(exc, ValueError)
assert backend.get_content("q2.json") == b'{"quarter": "Q2"}'
finally:
db.close()
MCP Agent Tools¶
Register Python tools and call them over MCP:
docs/examples/agent_mcp_tools.py
@tool(description="Add two integers and return their sum.")
def add_numbers(a: int, b: int) -> dict[str, int]:
"""Compute the sum of two integers."""
return {"sum": a + b}
def build_router() -> JSONRPCRouter:
"""Create a JSON-RPC 2.0 router exposing tools/list and tools/call."""
router = JSONRPCRouter()
tools = {add_numbers.name: add_numbers}
async def handle_list(_params: Any = None, _ctx: Any = None) -> dict[str, Any]:
return {
"tools": [
{
"name": item.name,
"description": item.description,
"inputSchema": item.input_schema,
}
for item in tools.values()
]
}
router.register("tools/list", handle_list)
return router
async def run_tool_workflow() -> None:
"""Validate JSON-RPC tool discovery and execute a typed ToolCall."""
assert add_numbers.input_schema["required"] == ["a", "b"]
router = build_router()
raw_req = encode_json_bytes({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})
raw_res = await router.dispatch_payload(raw_req)
assert raw_res is not None
decoded = decode_json(raw_res)
assert decoded["result"]["tools"][0]["name"] == "add_numbers"
results = await execute_tool_calls(
{add_numbers.name: add_numbers},
[ToolCall(id="call-1", name="add_numbers", arguments={"a": 19, "b": 23})],
)
assert len(results) == 1
assert not results[0].is_error
assert results[0].output == {"sum": 42}
def main() -> None:
"""Execute the agent tool schema and JSON-RPC router workflow."""
asyncio.run(run_tool_workflow())
Vector Embeddings & Search¶
Embed text into shared memory, truncate vectors, and run cosine similarity search:
docs/examples/embeddings_app.py
class SearchRequest(msgspec.Struct):
"""Query payload for semantic vector search."""
query: str
documents: list[str]
top_k: int = 2
class SearchHit(msgspec.Struct):
"""Ranked semantic search match."""
index: int
score: float
document: str
class SearchResponse(msgspec.Struct):
"""Top-k semantic search response."""
dimensions: int
hits: list[SearchHit]
def build_embedder() -> Embedder:
"""Create a deterministic shared-memory embedder for local execution."""
return StaticEmbedder(dimensions=512)
class VectorSearchController(Controller):
"""Controller exposing semantic search over shared-memory vectors."""
path = "/search"
dependencies = {"embedder": Provide(build_embedder, scope="singleton")}
@post("/")
async def search(
self,
body: SearchRequest,
embedder: Annotated[Embedder, Inject()],
) -> SearchResponse:
"""Embed query and documents into SHM and return top-k matches."""
query_view = await embedder.embed_query(body.query)
doc_batch = await embedder.embed_many(body.documents)
short_query = query_view.truncate(256)
short_docs = doc_batch.truncate(256)
ranked = embedder.similarity_search(
short_query,
short_docs,
top_k=body.top_k,
)
hits = [
SearchHit(
index=match.index,
score=match.score,
document=body.documents[match.index],
)
for match in ranked
]
return SearchResponse(dimensions=short_docs.dimensions, hits=hits)
def create_app() -> App:
"""Mount VectorSearchController onto a Vertebra App."""
return App(route_handlers=[VectorSearchController])
async def run_embedding_workflow() -> None:
"""Verify zero-copy PEP 3118 buffer views, truncation, and top-k search."""
embedder = build_embedder()
docs = [
"Shared-memory ring buffers eliminate IPC serialization copies.",
"Cloud SQL and AlloyDB mTLS dialers rotate ephemeral certificates.",
"Matryoshka truncation slices leading dimensions and re-normalizes.",
]
query_view = await embedder.embed_query("shared-memory IPC rings")
batch_view = await embedder.embed_many(docs)
raw_view = memoryview(batch_view)
assert raw_view.ndim == 2
assert raw_view.shape == (3, 512)
truncated_query = query_view.truncate(256)
truncated_batch = batch_view.truncate(256)
assert truncated_query.dimensions == 256
assert truncated_batch.dimensions == 256
pg_wire = truncated_query.to_pgvector_bytes()
oracle_wire = truncated_query.to_oracle_bytes()
assert len(pg_wire) == 4 + 256 * 4
assert oracle_wire[:4] == b"\xdb\x01\x02\x00"
hits = embedder.similarity_search(truncated_query, truncated_batch, top_k=2)
assert len(hits) == 2
assert hits[0].index == 0
assert hits[0].score >= hits[1].score
def main() -> None:
"""Mount the vector search app and run the shared-memory workflow."""
app = create_app()
assert len(app.routes) == 1
asyncio.run(run_embedding_workflow())