FastAPI Integration & Middlewares
Relevant source files
The following files were used as context for generating this wiki page:
The Forze FastAPI integration connects Forze handlers and execution logic to the FastAPI web framework. It provides automated route generation from operation registries, identity binding through specialized middlewares, and comprehensive error mapping to standard HTTP status codes. This integration ensures that domain logic remains framework-agnostic while benefiting from FastAPI's high-performance asynchronous capabilities.
Sources: skills/forze-fastapi-interface/SKILL.md:1-12, skills/forze-wiring/SKILL.md:154-159
Lifecycle & Runtime Context
All FastAPI routes integrated with Forze require an active ExecutionRuntime scope. This is managed via an asynchronous context manager in the FastAPI lifespan, ensuring connection pools and dependencies are properly started and drained.
Context Dependency
A ctx_dep (context dependency) function is used to resolve the ExecutionContext for each request by calling runtime.get_context(). This ensures that handlers have access to the necessary ports and metadata within the request lifecycle.
The diagram shows the relationship between the FastAPI lifespan and the Forze execution scope.
Sources: skills/forze-fastapi-interface/SKILL.md:16-36, skills/forze-wiring/SKILL.md:180-192
Generated Routes & Registries
Forze projects frozen OperationRegistry instances onto FastAPI APIRouter objects. This allows developers to generate full sets of CRUD or domain-specific routes automatically from descriptors.
Route Styles
| Style | Description | Example Path |
|---|---|---|
rest | Resource-oriented paths using standard verbs. | GET /notes/{id} |
rpc | Operation-named paths with IDs in query parameters. | GET /notes/get?id={id} |
Attachment Helpers
attach_document_routes: Projects CRUD operations (Get, List, Create, Update, Delete).attach_search_routes: Projects search operations asPOST /<op>with filter bodies.attach_storage_routes: Projects multipart upload and raw-bytes download operations.attach_authn_routes: Projects authentication flows like login, logout, and password management.
Sources: skills/forze-fastapi-interface/SKILL.md:38-66, tests/unit/test_forze_fastapi/test_routes_authn.py:46-56
Middleware Architecture
Middlewares in Forze act as the "boundary" where external request metadata and credentials are bound to the internal ExecutionContext.
Core Middlewares
- SecurityContextMiddleware: Binds
AuthnIdentityandTenantIdentityfrom headers or cookies. It derives OpenAPI security schemes from theAuthnRequirementconfiguration. - InvocationMetadataMiddleware: Binds call-level metadata such as
execution_idandcorrelation_id. It can also honor theX-Forze-Deadline-Budgetheader. - LoggingMiddleware: Provides structured access logs, scrubbing sensitive token material or passwords before output.
- CustomHeadersMiddleware: Injects static or dynamic (sync/async) headers into the response.
This flowchart illustrates the order of middleware execution and how identity/metadata is injected into the ExecutionContext.
Sources: skills/forze-fastapi-interface/SKILL.md:88-120, skills/forze-auth-tenancy-secrets/SKILL.md:28-45, tests/unit/test_forze_fastapi/test_routes_authn.py:300-315
Error Handling & Observability
Forze maps domain-specific CoreException instances to standard HTTP responses using register_exception_handlers(app).
HTTP Status Mapping
| Exception Kind | HTTP Status | Description |
|---|---|---|
not_found | 404 | Resource missing |
conflict | 409 | Duplicate key or revision conflict |
validation | 422 | Invalid input (Pydantic errors) |
authentication | 401 | Authentication failed or missing |
authorization | 403 | Permission denied |
throttled | 429 | Rate limit reached (retryable) |
timeout | 504 | Invocation time budget exceeded |
Sources: skills/forze-observability-errors/SKILL.md:12-25, skills/forze-fastapi-interface/SKILL.md:107-111
Security Configuration
The apply_openapi_security(app, requirement) helper ensures that the generated OpenAPI documentation accurately reflects the authentication requirements. It derives securitySchemes from the AuthnRequirement used by SecurityContextMiddleware.
Authentication Requirement Ingress
Ingress methods can be configured for various credential sources:
HeaderTokenAuthn: Bearer tokens in theAuthorizationheader.HeaderApiKeyAuthn: API keys in a custom header (e.g.,X-API-Key).CookieTokenAuthn: Tokens stored in HTTP-only cookies.
Sources: skills/forze-fastapi-interface/SKILL.md:67-75, skills/forze-auth-tenancy-secrets/SKILL.md:28-45
Conclusion
The FastAPI integration serves as the primary ingress point for Forze-based services. By automating route generation and centralizing identity/metadata binding in middlewares, it allows developers to focus on domain logic while maintaining a robust, observable, and secure HTTP interface. This structure ensures that domain handlers remain "clean" and only interact with logical identities resolved at the system boundary.
Sources: skills/forze-fastapi-interface/SKILL.md:113-120, skills/forze-wiring/SKILL.md:214-222