Python SDK Documentation
Last Updated: October 15, 2026
Overview
The Careflow SDK provides a structured way for backend services to interact with the Careflow App Server. It encapsulates all API calls, HMAC signing, output publishing, input subscription, session validation, deployment metadata retrieval, and real-time WebSocket streaming. It mirrors the .NET Careflow SDK in surface and behavior, adapted to Python idioms (Pydantic models, typed responses, async for streaming).
The SDK contains one primary package with several logical sub-packages:
careflow_sdk
The primary package, containing CareflowClient and AsyncCareflowClient, which serve as the main entry points for all SDK operations, plus re-exported ClientOptions and __version__.
careflow_sdk.core
For core infrastructure components including ClientOptions (configuration + environment resolution), shared constants, and HTTP response/envelope handling.
careflow_sdk.models
For request and response models (Pydantic v2). Contains the request-model base types, App/Connector/Pipeline request models, streaming models, the ResponseModel[T] envelope, and all typed response payloads.
careflow_sdk.services
For service implementations exposed by the client (AppService, ConnectorService, PipelineService, StreamingService) plus their Careflow* concrete classes (sync and async).
careflow_sdk.exceptions
For custom exception types specific to the SDK, plus the ErrorFactory/ErrorCode machinery that maps HTTP status codes and broker error codes to those exceptions.
careflow_sdk.utils
For consumer-facing helpers; currently verify_signature for verifying inbound HMAC-signed webhook payloads.
This structure is reflected in usage:
App calls:
resp = client.app.get_deployment(GetDeploymentRequestModel())Connector calls:
from careflow_sdk.models import ConnectorPublishRequestModel
client.connector.publish(ConnectorPublishRequestModel(topic="topic_1", data={"hello": "world"}))Installation
pip install careflow-sdkRequirements: Python 3.11+. The SDK depends on careflow-wsgateway-client, published to a private Azure Artifacts feed — see the .NET-equivalent NuGet Feed setup section for the pip analogue, or Getting Started with Python.
Initialization
Import the SDK package and create a CareflowClient. With no arguments it resolves every option from environment variables:
from careflow_sdk import CareflowClient
client = CareflowClient()To override URLs, credentials, mTLS certificates, or other settings, pass a ClientOptions value to the constructor:
from careflow_sdk import CareflowClient, ClientOptions
options = ClientOptions(
controller_base_url="https://qa-controller.careflow.ca",
connector_base_url="https://qa-connector.careflow.ca",
ws_gateway_base_url="wss://qa-wsgateway.careflow.ca",
client_id="your-client-id",
client_secret="your-client-secret",
connector_secret="your-connector-secret",
cert="/path/to/client.cert.pem",
key="/path/to/client.key.pem",
ca_bundle_path="/path/to/ca-bundle.pem",
verify_ssl=True,
timeout=30.0,
max_retry=3,
)
client = CareflowClient(options)Environment variable defaults supported by ClientOptions:
CAREFLOW_SDK_CONTROLLER_BASE_URL
CAREFLOW_SDK_CONNECTOR_BASE_URL
CAREFLOW_SDK_WS_GATEWAY_BASE_URL
CAREFLOW_SDK_CLIENT_ID
CAREFLOW_SDK_CLIENT_SECRET
CAREFLOW_SDK_CONNECTOR_SECRET
CAREFLOW_SDK_CLIENT_CERT_PATH
CAREFLOW_SDK_CLIENT_KEY_PATH
CAREFLOW_SDK_CA_BUNDLE_PATH
CAREFLOW_SDK_VERIFY_SSL
CAREFLOW_SDK_TIMEOUT
CAREFLOW_SDK_MAX_RETRY_COUNT
Required options are resolved lazily — they only raise CareflowInvalidDataError when a call actually needs them (e.g. App calls need controller_base_url; streaming needs ws_gateway_base_url and connector_secret).
ClientOptions fields are read-only after construction; pass all values at construction time or via environment variables.
Loading a
.envfile: the SDK reads process environment variables only; it does not parse.envfiles. If you keep config in a.env, load it into the environment yourself before constructing the client (e.g.python-dotenv'sload_dotenv(),set -a; source .env, or docker-compose'senv_file:).
careflow_sdk
CareflowClient
CareflowClient is the main SDK entry point. It exposes four service properties, each constructed on first access and cached for the client's lifetime:
appconnectorstreamingpipeline
It also owns the shared HTTP configuration for:
- Base URLs
- Authentication secrets
- Retry behavior
- Timeout behavior
- SSL verification
- Client certificates
- Custom CA trust bundles
The SDK supports scoped copies of the client with modified configuration:
scoped = client.with_options(connector_secret="other-secret")
scoped.connector.publish(...)
# Equivalent, per-service (returns a rebound service on a scoped client):
client.connector.with_options(connector_secret="other-secret").publish(...)with_options accepts the same keyword options as the ClientOptions constructor. Omitting an option carries the current value over; passing an explicit None clears it back to env-var/default resolution. The original client is left unchanged, and the underlying connection pools are shared with the copy — closing them is the original owner's job.
Lifecycle
The client owns HTTP connection pools. Close them with close() when done, or use the client as a context manager:
with CareflowClient(options) as client:
client.connector.publish(...)For custom transport needs (corporate proxy, custom TLS, test stubbing), pass your own pre-configured httpx2.Client; it is then used for every request as-is and never closed by the SDK:
client = CareflowClient(options, http_client=httpx2.Client(proxy="http://proxy:3128"))AsyncCareflowClient
For asyncio applications, AsyncCareflowClient mirrors CareflowClient with awaitable methods (matching the .NET SDK, whose API is async-only). It takes the same ClientOptions and exposes the same app, connector, pipeline, and streaming services; only the call sites change (await, and async with / aclose() for teardown). Pass an httpx2.AsyncClient for custom transport.
from careflow_sdk import AsyncCareflowClient, ClientOptions
from careflow_sdk.models import ConnectorPublishRequestModel
async with AsyncCareflowClient(ClientOptions(...)) as client:
res = await client.connector.publish(ConnectorPublishRequestModel(topic="t", data={...}))Streaming is identical on both clients — client.streaming.connect(...) returns the same async WSGatewayStream (see the Streaming section below).
careflow_sdk.services
The careflow_sdk.services namespace contains the service ABCs used by CareflowClient/AsyncCareflowClient. Each service method takes a single request model and returns a ResponseModel[T] — the one exception is PipelineService, which dispatches commands by name and so takes plain arguments. On CareflowClient these methods are synchronous; on AsyncCareflowClient they are awaitable.
AppService / CareflowAppService
The App service provides high-level functions for interacting with App Server endpoints. All App requests are signed by default — the controller rejects unsigned App requests. Pass require_signing=False on the request model to suppress the HMAC headers (useful only for exercising the rejection path).
get_deployment
def get_deployment(
request_model: GetDeploymentRequestModel | None = None
) -> ResponseModel[DeploymentData]Retrieve deployment metadata.
Maps to: GET /api/v1/deployment
Deprecated:
client.app.publish,subscribeandflushwill be removed in a future major version. Use theclient.connectorequivalents instead. They now call the connector service, so they needconnector_base_url,connector_secretand the mTLS settings, andrequire_signinghas no effect. Each emits aDeprecationWarningand logs oneWARNINGper client on thecareflow_sdklogger on first use. Return types are unchanged, but subscribe now returns one connector page per call instead of every waiting record.
publish
def publish(request_model: AppPublishRequestModel) -> ResponseModel[AppPublishResult]Submit an App-level payload to a deployment topic.
Maps to: POST /data-stream/publish (connector). body.status is "success".
from careflow_sdk.models import AppPublishRequestModel
client.app.publish(AppPublishRequestModel(
topic="output_topic",
data={"resourceType": "Patient", "id": "test-patient-001"},
))subscribe
def subscribe(request_model: AppSubscribeRequestModel) -> ResponseModel[AppSubscribeResult]Poll for App output from a topic.
Maps to: GET /data-stream/subscribe (connector). body.data is a list of each record's message (or the record itself when it has none).
from careflow_sdk.models import AppSubscribeRequestModel
resp = client.app.subscribe(AppSubscribeRequestModel(topic="input_topic"))flush
def flush(request_model: AppFlushRequestModel) -> ResponseModel[AppSubscribeResult]Flush a deployment topic's index to the latest offset. Seeks the consumer to the end of the topic and commits that offset without returning records, so subsequent subscribe calls only see newly published data.
Maps to: GET /data-stream/subscribe (connector) with seekToLatest=true
from careflow_sdk.models import AppFlushRequestModel
client.app.flush(AppFlushRequestModel(topic="input_topic"))get_users
def get_users(request_model: GetUsersRequestModel | None = None) -> ResponseModel[UsersData]Retrieve App users.
Maps to: GET /api/v1/users
from careflow_sdk.models import GetUsersRequestModel
resp = client.app.get_users(GetUsersRequestModel())request_patients
def request_patients(
request_model: PatientsRequestModel | None = None
) -> ResponseModel[PatientsRequestResult]Trigger a patient list feed through Careflow Publisher and retrieve the matched patient topics.
Maps to: GET /api/v1/patients/request
from careflow_sdk.models import PatientsRequestModel
resp = client.app.request_patients(PatientsRequestModel())Raises when the App is not configured for patient requests:
CareflowMissingProjectError— no project is assigned to the App.CareflowMissingPatientListError— a project is assigned but no patient list is configured, either because the project has no associated patient list or its patient-list topic has not been assigned.
get_session
def get_session(request_model: GetSessionRequestModel) -> ResponseModel[SessionData]Validate and retrieve session information for an App user session.
Maps to: GET /api/v1/session
from careflow_sdk.models import GetSessionRequestModel
resp = client.app.get_session(GetSessionRequestModel(
session_token="user-session-token",
))ConnectorService / CareflowConnectorService
The Connector service provides access to data-stream endpoints. Connector requests are authenticated by connector_secret (not HMAC signing).
publish (Connector)
def publish(request_model: ConnectorPublishRequestModel) -> ResponseModel[PublishResult]Publish records to a connector topic.
Maps to: POST /data-stream/publish
from careflow_sdk.models import ConnectorPublishRequestModel
client.connector.publish(ConnectorPublishRequestModel(
topic="output_topic",
data={"resourceType": "Patient", "id": "test-patient-001", "active": True},
))subscribe (Connector)
def subscribe(request_model: ConnectorSubscribeRequestModel) -> ResponseModel[SubscribeResult]Fetch records from a connector topic.
Maps to: GET /data-stream/subscribe
from careflow_sdk.models import ConnectorSubscribeRequestModel
resp = client.connector.subscribe(ConnectorSubscribeRequestModel(topic="input_topic"))flush (Connector)
def flush(request_model: ConnectorFlushRequestModel) -> ResponseModel[SubscribeResult]Flush a connector topic's index to the latest offset. The connector seeks the consumer to the end of the topic and commits that offset without returning records, so subsequent subscribe calls only see newly published data. Returns an empty result with total of 0.
Maps to: GET /data-stream/subscribe with seekToLatest=true
from careflow_sdk.models import ConnectorFlushRequestModel
client.connector.flush(ConnectorFlushRequestModel(topic="input_topic"))PipelineService / CareflowPipelineService
The Pipeline service provides command-dispatch access to broker pipeline operations over a single endpoint, POST /api/v1/pipeline. The command is named in the request body rather than by route, so commands the broker adds later work without an SDK release — there are deliberately no per-command methods and no response models.
execute
def execute(
command: str,
parameters: dict | None = None,
*,
require_signing: bool = True,
) -> ResponseModel[dict[str, Any]]Run a single pipeline command. There is no per-command response model — the decoded response body is returned as-is.
Maps to: POST /api/v1/pipeline
from careflow_sdk.models import PipelineCommand
result = client.pipeline.execute(command=PipelineCommand.DEPLOYMENT_GET)
print(result.status_code) # 200
print(result.body) # the server's decoded JSON, as a plain dictThe request body is exactly {"command": ..., "parameters": ...}; parameters defaults to {} when omitted.
Like App requests, pipeline calls are signed by default; the HMAC headers cover the complete body. Pass require_signing=False to suppress them:
client.pipeline.execute(command=PipelineCommand.DEPLOYMENT_GET, require_signing=False)PipelineCommand lists the commands known at the time of this SDK release, for autocomplete and typo safety only — it is not a whitelist:
PipelineCommand.DEPLOYMENT_GET(pipeline.deployment.get)PipelineCommand.DEPLOYMENT_LIST(pipeline.deployment.list)PipelineCommand.DEPLOYMENT_STATUS(pipeline.deployment.status)PipelineCommand.ARTIFACT_GET(pipeline.artifact.get)PipelineCommand.RUN_START(pipeline.run.start)PipelineCommand.RUN_STATUS(pipeline.run.status)PipelineCommand.RUN_STOP(pipeline.run.stop)
Plain strings are equally valid, which is what lets new broker commands work unchanged:
client.pipeline.execute(command="pipeline.some.future.command")The only client-side validation is that command is a non-empty string and parameters is a dictionary; either failure raises CareflowInvalidDataError before anything is sent.
On AsyncCareflowClient the same call is awaitable:
result = await async_client.pipeline.execute(command=PipelineCommand.DEPLOYMENT_GET)Command parameters
| Command | Parameters |
|---|---|
pipeline.deployment.get | None. Returns the app's pipelines under result.deployment_pipelines.models. |
pipeline.deployment.list | Not implemented on the controller yet; returns NOT_IMPLEMENTED. |
pipeline.deployment.status | deployment_instance_uuid |
pipeline.artifact.get | deployment_instance_uuid, config_file (a name from deployment.status's artifact_files). The file comes back base64-encoded in result.content. |
pipeline.run.start | deployment_instance_uuid, optional params (pipeline parameters, at most 64 KiB as JSON). Returns the run's deployment_instance_run_uuid. |
pipeline.run.status | deployment_instance_uuid, deployment_instance_run_uuid |
pipeline.run.stop | deployment_instance_uuid, deployment_instance_run_uuid |
deployment_instance_uuid always comes from pipeline.deployment.get (models[].model_artifacts[].deployment_instance_uuid). Read it at runtime rather than storing it, because it changes when the app is redeployed.
Running a deployed pipeline
Find the workflow, start a run, then poll until the run reaches completed, failed or stopped:
import time
from careflow_sdk.models import PipelineCommand
deployment = client.pipeline.execute(command=PipelineCommand.DEPLOYMENT_GET)
models = deployment.body["result"]["deployment_pipelines"]["models"]
workflow = next(model for model in models if model["workflow"] == "patient-analysis-workflow")
instance_uuid = workflow["model_artifacts"][0]["deployment_instance_uuid"]
run = client.pipeline.execute(
command=PipelineCommand.RUN_START,
parameters={
"deployment_instance_uuid": instance_uuid,
"params": {"input": "s3://bucket/sample.fastq"},
},
)
run_uuid = run.body["result"]["deployment_instance_run_uuid"]
while True:
time.sleep(10)
run_status = client.pipeline.execute(
command=PipelineCommand.RUN_STATUS,
parameters={"deployment_instance_uuid": instance_uuid, "deployment_instance_run_uuid": run_uuid},
)
status = run_status.body["result"]["status"]
if status in ("completed", "failed", "stopped"):
breakTo end a run early, send PipelineCommand.RUN_STOP with the same two UUIDs. A workflow with more than one artifact should pick its artifact explicitly, for example by label, instead of taking the first.
Run statuses
| Status | Meaning |
|---|---|
pending | The start was accepted and the run is recorded. |
starting | The run is being launched. |
running | The pipeline is executing. |
completed | The pipeline finished successfully. Final. |
failed | The pipeline could not be launched or finished with an error. Final. |
stopping | A stop was requested and the run is shutting down. |
stopped | The run was stopped before it finished. Final. |
A successful pipeline.run.start only means the run was accepted; poll pipeline.run.status to follow it. Each start creates a separate run, and earlier runs stay available to pipeline.run.status.
Response fields
pipeline.run.statusalso returnsrequested_at,started_atandcompleted_at(Unix seconds,nulluntil reached),exit_code,error_message,engine_run_id,run_nameandtrace(one object per pipeline task with string values,nulluntil the engine writes one).pipeline.run.stopnormally returnsstopping. Only the named run is affected, repeating the stop is safe, and stopping a run that has already ended returns its final status unchanged.pipeline.deployment.statusreturnsdeployment_pipeline,deployment_instanceandartifact_files.deployment_instance.statusis the pipeline deployment's own status (pending,startedorstopped), not a run's.artifact_files[].config_fileis the exact, case-sensitive name to pass topipeline.artifact.get.pipeline.artifact.getreturnsfilename,content_type,size(decoded bytes) and the file base64-encoded incontent.
Errors
The controller reports command failures as HTTP 200 with a responseStatus body instead of result. execute turns these into exceptions, so a returned body always has result:
- A numeric
codemaps to the matching error, for example404toCareflowNotFoundErrorand500toCareflowServerError. - Authentication codes (
MISSING_HEADERS,INVALID_SIGNATURE,EXPIRED_TIMESTAMP, …) map to their specific errors. - Other codes, such as
INVALID_PARAMETERS,RUN_FAILED,STATUS_FAILED,ARTIFACT_FAILEDorUNKNOWN_COMMAND, raiseCareflowClientError.
The error message is the controller's responseStatus.message.
StreamingService / CareflowStreamingService
The Streaming service provides real-time WebSocket streaming from the Careflow streaming gateway. It is independent from the App and Connector services as it communicates directly with the streaming gateway rather than the App or Connector servers.
connect
def connect(
stream_model: ConnectorStreamModel,
options: ConnectOptions | None = None,
) -> wsgateway.WSGatewayStreamOpen a real-time WebSocket stream. Unlike subscribe which polls, connect is push-based — the gateway pushes messages to you as they arrive. Supports subscribing to multiple topics in a single connection. Returns the gateway's WSGatewayStream — an async iterator you consume with async for (each item is a wsgateway.WsMessage), also usable as an async with block.
CAREFLOW_SDK_WS_GATEWAY_BASE_URL and CAREFLOW_SDK_CONNECTOR_SECRET are required environment variables (configured by default from Careflow Orchestrator).
import asyncio
from careflow_sdk import CareflowClient, ClientOptions
from careflow_sdk.models import ConnectorStreamModel
client = CareflowClient(ClientOptions(
ws_gateway_base_url="wss://qa-wsgateway.careflow.ca",
connector_secret="your-connector-secret",
))
async def main():
# `async with` closes the connection deterministically on any exit.
async with client.streaming.connect(ConnectorStreamModel(topics=["input_topic"])) as stream:
async for msg in stream:
print(msg.topic, msg.value) # msg is a wsgateway.WsMessage
asyncio.run(main())Resolving the topic name from deployment metadata before streaming:
async def main():
deployment = client.app.get_deployment()
topic = next(t for t in deployment.body.deployment_yaml.topics if t.name == "test")
async for msg in client.streaming.connect(ConnectorStreamModel(topics=[topic.topic])):
print(msg.offset, msg.value)This is necessary to resolve the topic name of deployment-bound topics.
Stopping the stream. The gateway does not resend a message once it has delivered it to the client, so any messages already buffered on your side will be lost if you stop without draining them. Two ways to stop:
- Graceful (lossless) —
stream.close(). Call it and keep iterating.close()stops pulling new messages but leaves the already-delivered ones in the buffer, so your loop finishes processing everything the gateway handed over before it ends. Use this for any shutdown where dropping in-flight messages would be data loss. If the buffer can't drain withinclose_timeoutthe connection is force-closed and iteration raisesCloseTruncatedError— signalling that some delivered messages went unprocessed. - Abrupt —
break/stream.aclose()/ leaving theasync withblock. Tears the connection down immediately and discards whatever is still buffered. The gateway won't resend those, so use this only when you don't need the in-flight messages.
async with client.streaming.connect(ConnectorStreamModel(topics=["input_topic"])) as stream:
async for msg in stream:
handle(msg)
if should_stop:
stream.close() # graceful: do NOT break — let the loop drain and finishNotes:
- Currently the Careflow streaming gateway only supports one connection per connector secret. It is planned to increase this connection limit in the future, and it is not expected to break existing applications.
- On disconnect,
connect()automatically reconnects with exponential backoff and resumes from the latest offset. Transient errors (network failures, malformed messages, unexpected server responses) are reported viaon_errorand retried; only authentication rejection, invalid topics, cancellation, and reconnect exhaustion end the stream. - To skip the backlog and only receive data published after connecting, set
seek_to_latest=TrueonConnectorStreamModel. - It is recommended to open one connection on the backend and broadcast topic stream data to clients as server-sent events, in order to prevent connection limit exhaustion.
careflow_sdk.models
The careflow_sdk.models namespace contains the request and response models used by the SDK. All are Pydantic v2 models. The wire format is snake_case.
Request Model Base Types
CallModel # abstract base; resolves the target base URL
└── RequestModel # HTTP request machinery: headers, body/query, signing hook
├── AppRequestModel # base "/api/v1"; adds require_signing + HMAC signing
└── ConnectorRequestModel # base "/data-stream"; injects clientSecret into body/queryRequestModel provides shared machinery for query-string construction, default request headers, body serialization, response validation, and request URL generation.
Default headers added to every request:
content-type: application/json; charset=utf-8accept: application/jsonuser-agent: Careflow-SDK-Python/<package version>request-timeout: <timeout seconds>
For POST endpoints, the model's data field is serialized to a compact JSON string and sent as the data field of the request body (double-encoded), ensuring the bytes sent match the bytes signed.
App Request Models
App request models live under careflow_sdk.models and share the require_signing field.
GetDeploymentRequestModel
Used by: client.app.get_deployment()
Constructor fields:
| Field | Type | Description |
|---|---|---|
require_signing | bool | When True, attaches App signing headers to the request. Default is True. |
AppPublishRequestModel
Used by: client.app.publish()
Constructor fields:
| Field | Type | Description |
|---|---|---|
topic | str | None | Target topic. |
data | Any | None | Payload sent (JSON-encoded) as the data field of the request body. |
require_signing | bool | No effect: the request goes to the connector service, which does not use App signing. |
AppSubscribeRequestModel
Used by: client.app.subscribe()
Constructor fields:
| Field | Type | Description |
|---|---|---|
topic | str | None | Target topic. Sent as a query parameter. |
require_signing | bool | No effect: the request goes to the connector service, which does not use App signing. |
AppFlushRequestModel
Used by: client.app.flush(). Sends seekToLatest=true automatically.
Constructor fields:
| Field | Type | Description |
|---|---|---|
topic | str | None | Target topic. Sent as a query parameter. |
require_signing | bool | No effect: the request goes to the connector service, which does not use App signing. |
GetUsersRequestModel
Used by: client.app.get_users()
Constructor fields:
| Field | Type | Description |
|---|---|---|
require_signing | bool | When True, attaches App signing headers to the request. Default is True. |
GetSessionRequestModel
Used by: client.app.get_session()
Constructor fields:
| Field | Type | Description |
|---|---|---|
session_token | str | None | Session token to validate. Sent as a query parameter. |
require_signing | bool | When True, attaches App signing headers to the request. Default is True. |
PatientsRequestModel
Used by: client.app.request_patients()
Constructor fields:
| Field | Type | Description |
|---|---|---|
require_signing | bool | When True, attaches App signing headers to the request. Default is True. |
Connector Request Models
Connector request models live under careflow_sdk.models and share an optional per-request secret override.
ConnectorPublishRequestModel
Used by: client.connector.publish()
Constructor fields:
| Field | Type | Description |
|---|---|---|
topic | str | None | Target topic. |
data | Any | None | Payload sent (JSON-encoded) as the data field of the request body. |
connector_secret | str | None | Optional connector secret override. If omitted, the SDK uses ClientOptions.connector_secret. |
ConnectorSubscribeRequestModel
Used by: client.connector.subscribe()
Constructor fields:
| Field | Type | Description |
|---|---|---|
topic | str | None | Target topic. Sent as a query parameter. |
connector_secret | str | None | Optional connector secret override. If omitted, the SDK uses ClientOptions.connector_secret. |
ConnectorFlushRequestModel
Used by: client.connector.flush(). Sends seekToLatest=true automatically.
Constructor fields:
| Field | Type | Description |
|---|---|---|
topic | str | None | Target topic. Sent as a query parameter. |
connector_secret | str | None | Optional connector secret override. If omitted, the SDK uses ClientOptions.connector_secret. |
Pipeline Request Model
Pipeline request models live under careflow_sdk.models.
PipelineExecuteRequestModel
Used by: client.pipeline.execute(). Subclasses AppRequestModel, so it shares the /api/v1 namespace, controller host, and HMAC scheme with the App API.
Constructor fields:
| Field | Type | Description |
|---|---|---|
command | str | Pipeline command to run, sent as the command field of the JSON request body. Must be a non-empty string; raises CareflowInvalidDataError otherwise. See PipelineCommand for known values. |
parameters | dict | None | Command parameters sent as the parameters field of the JSON request body. Defaults to an empty dict when omitted. |
require_signing | bool | When True, attaches App signing headers to the request. Default is True. |
Streaming Request Model
Streaming request models live under careflow_sdk.models.
ConnectorStreamModel
Used by: client.streaming.connect()
Constructor fields:
| Field | Type | Description |
|---|---|---|
topics | list[str] | One or more topics to subscribe to. |
seek_to_latest | bool | When True, skips the backlog and only receives data published after the connection is established. Default is False. |
ConnectOptions
Optional second argument to client.streaming.connect(). A plain dataclass; every field defaults to None ("leave the gateway default in place"), so only the fields you set are forwarded.
Constructor fields:
| Field | Type | Description |
|---|---|---|
reconnect_enabled | bool | None | Whether to automatically reconnect on disconnect. Gateway default True. |
reconnect_interval | float | None | Initial delay between reconnect attempts (s). Gateway default 1.0. |
reconnect_max_interval | float | None | Maximum delay between reconnect attempts (s). Gateway default 30.0. |
reconnect_max_attempts | int | None | Maximum reconnect attempts before raising. Gateway default unlimited (0). |
connection_timeout | float | None | Timeout for establishing the WebSocket connection (s). Gateway default 10.0. |
auth_timeout | float | None | Timeout for completing the authentication handshake (s). Gateway default 5.0. |
max_queue_size | int | None | Messages buffered ahead of a slow consumer before backpressure is applied (0 = unbounded, nothing dropped). Gateway default 32. |
close_timeout | float | None | Seconds a graceful close() waits to finish draining before force-closing (raising CloseTruncatedError). Gateway default 30.0. |
keepalive_interval | float | None | Interval between WebSocket keep-alive frames on idle connections (0 = disabled). Gateway default 15.0. |
keepalive_timeout | float | None | Seconds to wait for a pong before treating the connection as dead and reconnecting. Gateway default 20.0. |
on_connect | Callable | None | Called when the connection is established and authenticated. |
on_disconnect | Callable | None | Called when the connection closes. |
on_reconnect | Callable | None | Called before each reconnect attempt, with (attempt, backoff). |
on_error | Callable | None | Called on stream errors, including transient ones (network errors, malformed messages) that are retried per the reconnect policy. |
Callbacks may be plain functions or coroutines. An unhandled exception raised by a callback is fatal: the stream terminates and the exception propagates, unwrapped, out of the connect() iterator (matching the .NET SDK). The one exception is on_error itself: since the stream is already failing, the original stream error is what propagates; an exception raised by the on_error handler is chained onto it (__context__).
Response Models
All successful service methods return:
ResponseModel[T]Which contains:
| Field | Type | Description |
|---|---|---|
status_code | int | The HTTP status code of the response. |
body | T | The deserialized, typed response payload. |
App response payload models:
DeploymentDataAppPublishResultAppSubscribeResultUsersDataSessionDataPatientsRequestResult
Connector response payload models:
PublishResultSubscribeResult
Pipeline response payload:
dict[str, Any]— no dedicated model. The decoded response body is returned as-is, since commands are not fixed to a per-command shape.
Notable response shapes:
AppPublishResult(publish) containsstatus: str | None("success").AppSubscribeResult(subscribe,flush) containsdata: Any | None, a list of each record'smessage(or the record itself when it has none).UsersDatacontainsapp_users: list[AppUser] | None.SessionDatacontainsuser: SessionUserEntry | None.PatientsRequestResultcontainstopics: list[PatientTopic] | None.PublishResultcontainsidandtopic.SubscribeResultcontainsdata_set_meta,records, andtotal.DataSetMeta→name,data_type,description,created_time,last_modified_time.SubscribeRecord→key,offset,partition,timestamp,topic,message(Any, the user-defined payload).DeploymentDatacontainsdeployment_yaml: DeploymentYaml | None, whosemodels[].artifacts[]each expose astorages: list[DeploymentStorage] | Nonewith per-storage provisioning metadata (label,storage_type(StorageType:DATABASE,BLOB,BLOCK),database_type(DatabaseType:POSTGRESQL,MYSQL,MONGODB,REDIS,RABBITMQ),size,provider,version,instance_type,root_disk_size,share_key,is_primary_share) —None/empty when the artifact has no storage configured. Both enums areStrEnums, so they compare equal to their lowercase value (storage.database_type == "mongodb"); unrecognised values parse asUNKNOWN. See Deployment Storage for using storages from an app.
Streaming messages:
wsgateway.WsMessage(imported fromwsgateway, notcareflow_sdk— a frozen dataclass mirroring the .NETCareflow.WsGateway.Models.WsMessagerecord).
| Field | Type | Description |
|---|---|---|
topic | str | None | The topic the message was received from. |
key | str | None | The message key, used for partitioning and ordering. |
value | Any | The message payload. |
partition | int | The partition the message was consumed from. Default 0. |
offset | int | The position of the message within its partition. Default 0. |
timestamp | int | Unix timestamp in milliseconds of when the message was produced. Default 0. |
Request Signing
App requests are signed by default. Signing can be suppressed per request with require_signing=False on App request models.
When signing is enabled, the SDK attaches:
x-app-uuidx-timestampx-signature
The signing headers are generated from:
client_idclient_secret- HTTP method
- Relative request path
- Serialized request body
Canonical string format:
METHOD
PATH
TIMESTAMP
SHA256(BODY)The body hash is computed over the serialized JSON body. If there is no body, the SDK signs the empty string.
App signing can be enabled for:
GetDeploymentRequestModelGetUsersRequestModelGetSessionRequestModelPatientsRequestModelcareflow_sdk.models.PipelineExecuteRequestModel
Connector Authentication
Connector requests do not use App signing headers.
Instead, the SDK sends clientSecret with connector requests:
- In the request body for
POST /data-stream/publish - In the query string for
GET /data-stream/subscribe
If a connector request model does not explicitly set connector_secret, the SDK falls back to ClientOptions.connector_secret.
If no connector secret is available, the SDK raises CareflowInvalidDataError.
Importing careflow_sdk installs a filter on the httpx2 logger that redacts the connector secret from its request-log line, since httpx2 logs every request at INFO with the full URL and connector reads carry the secret as a clientSecret query parameter.
WebSocket Streaming Authentication
connect() connects directly to the WsGateway using ClientOptions.connector_secret as the WebSocket authentication credential.
The gateway enforces one active connection per secret. Reconnect picks up from the latest offset, not from offset 0. If no connector secret is available, connect() raises CareflowInvalidDataError.
Response Handling and Exceptions
On success, SDK methods return ResponseModel[T].
On failure, the SDK raises an exception instead of returning an error response object.
CareflowError
├── CareflowIOError
│ └── CareflowSslError
├── CareflowInvalidDataError
└── CareflowApiError
├── CareflowClientError
│ ├── CareflowBadRequestError
│ │ └── CareflowValidationError
│ ├── CareflowUnauthorizedError
│ ├── CareflowForbiddenError
│ ├── CareflowNotFoundError
│ ├── CareflowRateLimitError
│ ├── CareflowMissingHeadersError
│ ├── CareflowInvalidTimestampError
│ ├── CareflowExpiredTimestampError
│ ├── CareflowInvalidSignatureError
│ └── CareflowUnknownAppIdError
├── CareflowServerError
│ └── CareflowAuthInternalError
├── CareflowMissingProjectError
├── CareflowMissingPatientListError
└── CareflowUnexpectedStatusCodeErrorEvery CareflowApiError exposes .status_code: int, .response_body: str, and .error_code (the broker responseStatus.code when present, else None).
HTTP status code mappings include:
400→CareflowBadRequestError401→CareflowUnauthorizedError403→CareflowForbiddenError404→CareflowNotFoundError429→CareflowRateLimitError611→CareflowMissingProjectError612→CareflowMissingPatientListError- Other
4xx→CareflowClientError 5xx→CareflowServerError
Structured error-code mappings include:
MISSING_HEADERS→CareflowMissingHeadersErrorINVALID_TIMESTAMP→CareflowInvalidTimestampErrorEXPIRED_TIMESTAMP→CareflowExpiredTimestampErrorINVALID_SIGNATURE→CareflowInvalidSignatureErrorUNKNOWN_APP_ID→CareflowUnknownAppIdErrorAUTH_INTERNAL_ERROR→CareflowAuthInternalErrorFORBIDDEN→CareflowForbiddenErrorBAD_REQUEST→CareflowBadRequestError- A
responseStatus.messagefield-validation array →CareflowValidationError— exposes.field_errors, where eachFieldErrorhas.paramand.message 611→CareflowMissingProjectError— raised byrequest_patientswhen no project is assigned to the App.612→CareflowMissingPatientListError— raised byrequest_patientswhen a project is assigned but no patient list is configured.
Transport or configuration errors may also surface as:
CareflowSslErrorCareflowIOErrorCareflowInvalidDataError
An HTML body on a success response (a proxy or misconfigured route) is surfaced as CareflowNotFoundError (404); on a non-2xx status the real status is kept. A non-JSON, non-HTML body raises CareflowServerError.
WebSocket streaming errors
Streaming (client.streaming.connect()) is the exception to the hierarchy above. Errors from the WebSocket gateway are not wrapped into CareflowError — they propagate as the underlying wsgateway exception types, imported and caught directly:
wsgateway.WSGatewayError
├── ConnectionError
├── AuthenticationError
│ ├── InvalidTopicError
│ └── ClientAlreadyConnectedError
├── ReconnectExhaustedError
└── CloseTruncatedErrorwsgateway.WSGatewayError→ base — catch this for any streaming failure.ConnectionError→ the connection to the gateway failed.AuthenticationError→ the connector secret was rejected.InvalidTopicError→ one or more requested topics are not provisioned.ClientAlreadyConnectedError→ the secret already has an active connection (one per secret).ReconnectExhaustedError→ reconnection attempts hitreconnect_max_attempts.CloseTruncatedError→ a gracefulclose()could not drain withinclose_timeout.
The one streaming error the SDK itself raises is CareflowInvalidDataError, when no connector secret is configured.
Retry Behavior
The client retries failed requests according to max_retry.
Retry behavior applies to:
429500502503504- I/O failures
A response x-should-retry header (true/false) overrides the status-based decision.
When present, the SDK honors:
Retry-AfterRetry-After-Ms
Otherwise it uses capped exponential backoff with full jitter. TLS/certificate failures (CareflowSslError) are never retried, since they are deterministic. Set max_retry=0 to disable retries.
Utilities
careflow_sdk.utils exposes helpers useful to consumers.
verify_signature
def verify_signature(payload: bytes, signature_header: str, secret: str) -> boolVerify an inbound HMAC-signed webhook payload. The expected header format is sha256=<base64>, where the base64 value is HMAC-SHA256 of the raw request body using the shared secret. Returns True only on a constant-time match.
from careflow_sdk.utils import verify_signature
if not verify_signature(request.body, request.headers["X-Careflow-Signature"], secret):
raise PermissionError("bad signature")End-to-End Example
import asyncio
from careflow_sdk import CareflowClient, ClientOptions
from careflow_sdk.models import (
ConnectorPublishRequestModel,
ConnectorStreamModel,
ConnectorSubscribeRequestModel,
GetDeploymentRequestModel,
GetSessionRequestModel,
GetUsersRequestModel,
PatientsRequestModel,
PipelineCommand,
)
client = CareflowClient(ClientOptions(
controller_base_url="https://qa-controller.careflow.ca",
connector_base_url="https://qa-connector.careflow.ca",
ws_gateway_base_url="wss://qa-wsgateway.careflow.ca",
client_id="your-client-id",
client_secret="your-client-secret",
connector_secret="your-connector-secret",
verify_ssl=True,
timeout=30.0,
max_retry=3,
))
# Retrieve deployment metadata
deployment = client.app.get_deployment(GetDeploymentRequestModel())
# Retrieve App users
users = client.app.get_users(GetUsersRequestModel())
# Request patient topics
patients = client.app.request_patients(PatientsRequestModel())
session = client.app.get_session(GetSessionRequestModel(session_token="tok"))
# Publish to a connector topic
client.connector.publish(ConnectorPublishRequestModel(topic="output_topic", data={"hello": "world"}))
# Fetch from a connector topic
sub = client.connector.subscribe(ConnectorSubscribeRequestModel(topic="input_topic"))
# Run a pipeline command
pipeline_result = client.pipeline.execute(command=PipelineCommand.DEPLOYMENT_GET)
# Real-time WebSocket stream
async def stream():
async for msg in client.streaming.connect(ConnectorStreamModel(topics=["output_topic", "input_topic"])):
print(f"[{msg.topic}] offset={msg.offset}: {msg.value}")
asyncio.run(stream())