hexastack-fastapi
FastAPI presentation adapter for Hexastack: automatic CQRS routing, database session middleware, exception mapping, and health check endpoints.
Part of the Hexastack Framework · Governed by Hexaqual.
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(...)). - Server-Sent Events (SSE) Real-Time Streaming: Native
ServerSentEventformatting andEventSourceResponsesupporting chunked transfer encoding, keep-alive heartbeat pings, and direct streaming queries onCqrsRouter.add_streaming_query. - WebSockets Real-Time Channel Manager & CQRS Bridge:
WebSocketConnectionManagermanaging connection pools, room/channel groupings, and broadcasts, alongsideWebSocketCqrsBridgemapping incoming socket JSON actions into CQRS Commands and Queries. - 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, logs HTTP request lifecycles, and captures HTTP RED metrics (HttpMetricsMiddleware) exposing a standard/metricsendpoint. - 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, HexastackFastApiConfig
├── adapters/ # routing decorators, SSE streaming, WebSockets, health endpoints, db_session middleware, dependencies, NiceGUI UI adapter
└── infra/ # create_fastapi_app, FastApiBootstrapper (order=30), exception handlers, correlation/logging middlewares
Key Exports
| Category | Exports |
|---|---|
| Application Factory | create_fastapi_app, FastApiBootstrapper (order=30) |
| Decorators | @api_command, @api_query, @feature_flag_route, @rate_limit, RouteMetadata |
| Dependencies | get_container, get_pipeline, get_feature_flags, require_feature, get_rate_limiter, require_rate_limit |
| Documentation Mounting | mount_zensical_docs, DocumentationNotFoundError, ZensicalDocsConfig |
| Exception Handlers | register_exception_handlers, domain_exception_handler |
| Middlewares | DbSessionMiddleware, AsyncDbSessionMiddleware, add_db_session_middleware, CorrelationMiddleware, HttpLoggingMiddleware |
| Rate Limiting | SlowapiRateLimiterAdapter, get_remote_address, get_user_or_ip_key, RateLimitConfig |
| Reactive UI (NiceGUI) | dispatch_command, dispatch_query, mount_devtools_dashboard, mount_ui_app, ui_page |
| Real-Time Streaming (SSE & WebSockets) | EventSourceResponse, ServerSentEvent, WebSocketConnectionManager, WebSocketCqrsBridge |
| 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"}
Metadata
Release files for hexastack-fastapi 0.10.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| hexastack_fastapi-0.10.1.tar.gz | 36.0 kB | Without provenance | Details for hexastack_fastapi-0.10.1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| hexastack_fastapi-0.10.1-py3-none-any.whl | Python 3 | none | any | Details for hexastack_fastapi-0.10.1-py3-none-any.whl |
Total release size: 84.7 kB
Release files / hexastack_fastapi-0.10.1.tar.gz
| Download URL | hexastack_fastapi-0.10.1.tar.gz |
|---|---|
| Size | 36.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
75fe395f98b4bcc7fd723abbf427dd4935e3dad4444471a08308552ad77745e5
|
|
BLAKE2b-256 checksum How to use checksums |
ae17056c779c9f3d10b2d3dd17390bf64f1b8fe544af00e5e9ec8ccde6f32923
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Release files / hexastack_fastapi-0.10.1-py3-none-any.whl
| Download URL | hexastack_fastapi-0.10.1-py3-none-any.whl |
|---|---|
| Size | 48.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
29e8ccaffefcb612613cdf31a0221efa1aa71e26a265ebd995e7d7d6e6d78bb2
|
|
BLAKE2b-256 checksum How to use checksums |
25e42fa4863dc4e5505adb87e29351655aa04e99059b6e4e9def40cf8d83ef48
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
Security for hexastack-fastapi 0.10.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.