hexastack-fastapi
FastAPI presentation adapter for Hexastack: automatic CQRS routing, database session middleware, exception mapping, and health check endpoints.
1. Overview & Capabilities
- Automatic CQRS Routing & Feature Gating: Map HTTP endpoints directly to
CommandBusPortorQueryBusPortusing@api_commandand@api_query, with native feature flag route guards (@feature_flag_routeandrequire_feature(...)). - Decoupled Database Session Middleware:
DbSessionMiddleware(sync) andAsyncDbSessionMiddleware(async) manage session-per-request lifecycles by consuming sessionmakers from DI without a hard dependency onhexastack-db. - Standardized Exception Handlers: Automatically translates domain exceptions (
EntityNotFoundError,UniqueConstraintViolationError,HexastackError) into appropriate HTTP status codes (404, 409, 500) and structured JSON error envelopes. - Observability & Correlation Middleware: Injects
X-Correlation-IDheaders and logs HTTP request lifecycles. - Built-in Health Checks: Configurable
/healthand/readyendpoints verifying container and subsystem readiness. - NiceGUI Reactive UI & DevTools Dashboard: Optional
[ui]presentation adapter providingui_page,dispatch_command,dispatch_query, and a zero-config interactive developer console (mount_devtools_dashboard) for inspecting CQRS buses, feature flags, and DI services.
2. Package Anatomy & Key Components
hexastack_fastapi/
├── domain/ # HealthStatus, HTTP error envelope models
├── adapters/ # create_app, routing decorators, health endpoints, db_session middleware, dependencies, NiceGUI UI adapter
└── infra/ # FastApiBootstrapper (order=30), exception handlers, correlation/logging middlewares
Key Exports
| Category | Exports |
|---|---|
| Application Factory | create_app, FastApiBootstrapper (order=30) |
| Decorators | @api_command, @api_query, @feature_flag_route, RouteMetadata |
| Dependencies | get_container, get_pipeline, get_feature_flags, require_feature |
| Documentation Mounting | mount_zensical_docs, DocumentationNotFoundError, ZensicalDocsConfig |
| Exception Handlers | register_exception_handlers, domain_exception_handler |
| Middlewares | DbSessionMiddleware, AsyncDbSessionMiddleware, add_db_session_middleware, CorrelationMiddleware, HttpLoggingMiddleware |
| Reactive UI (NiceGUI) | dispatch_command, dispatch_query, mount_devtools_dashboard, mount_ui_app, ui_page |
| Routing | CqrsRouter, autodiscover_routes |
| Testing, E2E & Demo Narration | create_test_client, check_openapi_conformance, EphemeralServer, ephemeral_server, find_free_port, smart_click, DemoNarrator, VIRTUAL_CURSOR_SCRIPT |
3. Monorepo & Sibling Relationships
graph TD
subgraph ClientRequests ["Client HTTP Inbound"]
HTTP["HTTP Client Requests"]
end
subgraph FastApiLayer ["hexastack-fastapi"]
APP["FastAPI Application"]
MW["Middleware (Correlation, HTTP Logging, DB Session)"]
ROUTER["CQRS Route Dispatcher"]
end
subgraph CQRSExecution ["hexastack-cqrs"]
CBUS["CommandBusPort"]
QBUS["QueryBusPort"]
end
subgraph DecoupledProviders ["Decoupled Providers (via DI)"]
DB_FACTORY["sessionmaker / async_sessionmaker (from hexastack-db)"]
LOG_PORT["LoggerPort (from hexastack-logging)"]
end
HTTP --> APP
APP --> MW
MW --> ROUTER
ROUTER -->|dispatches to| CBUS
ROUTER -->|dispatches to| QBUS
MW -. consumes session factory from DI .-> DB_FACTORY
MW -. consumes LoggerPort from DI .-> LOG_PORT
Explicit Dependencies (Direct)
hexastack-core: DI container, core ports, exception registry, and context propagation.hexastack-cqrs:CommandBusPortandQueryBusPortfor message dispatching.fastapi>=0.141.1: Web framework and ASGI routing.
Implied / Behavioral Relationships (DI-Mediated)
- Zero-Dependency DB Session Management:
DbSessionMiddlewaredynamically resolves SQLAlchemysessionmakerfrom DI without directly importinghexastack-db. - Telemetry Integration:
HttpLoggingMiddlewareoutputs structured request telemetry throughLoggerPort. - Exception Mapping: Registers global exception handlers translating core domain errors into standard HTTP error responses.
4. Installation
# Standalone install
pip install hexastack-fastapi
# With Uvicorn development server
pip install "hexastack-fastapi[web]" # or: pip install "hexastack[web]"
# Via umbrella package
pip install "hexastack[fastapi]"
5. Configuration Reference
[hexastack.fastapi]
title = "Hexastack API"
version = "1.0.0"
docs_url = "/docs"
openapi_url = "/openapi.json"
cors_origins = ["*"]
enable_correlation_header = true
6. Quickstart Example
from dataclasses import dataclass
from fastapi.testclient import TestClient
from hexastack_core.infra.bootstrap import bootstrap
from hexastack_cqrs.domain.query import Query
from hexastack_cqrs.infra.decorators import query_handler
from hexastack_fastapi.adapters.app import create_app
@dataclass(frozen=True)
class GetGreetingQuery(Query):
name: str
@query_handler(GetGreetingQuery)
class GetGreetingHandler:
def __call__(self, qry: GetGreetingQuery) -> dict:
return {"message": f"Hello, {qry.name}!"}
runtime = bootstrap(packages_to_scan=[__name__])
app = create_app(runtime)
client = TestClient(app)
response = client.get("/health")
print(response.json()) # {"status": "healthy"}
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
hexastack_fastapi-0.0.0.tar.gz
(25.0 kB
view details)
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 hexastack_fastapi-0.0.0.tar.gz.
File metadata
- Download URL: hexastack_fastapi-0.0.0.tar.gz
- Upload date:
- Size: 25.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
78a6f5972c20f9cd209e6f719d120a4305641ce23301e5ca260b2e6b8a6a044e
|
|
| MD5 |
378f3d0053e9b6c5b4631609d5a3f6bd
|
|
| BLAKE2b-256 |
db021378995ed7e9650f6c02ec7d6099d4221b4a63ebc9fe2b21d9f92c445300
|
File details
Details for the file hexastack_fastapi-0.0.0-py3-none-any.whl.
File metadata
- Download URL: hexastack_fastapi-0.0.0-py3-none-any.whl
- Upload date:
- Size: 36.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via:
uv/0.12.3 {"installer":{"name":"uv","version":"0.12.3","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
755b754d88b76b63ae52d4553e40b767493aad4d61cf981b7c3477d7542443e6
|
|
| MD5 |
68e6f6de445dc2db7919c4c7255ee62a
|
|
| BLAKE2b-256 |
3f7ce55414e750693ded06fbf8aa0e028ad126e2ceb0c8a0271bce73a8b85bea
|