CareflowDocumentation

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:

python
resp = client.app.get_deployment(GetDeploymentRequestModel())

Connector calls:

python
from careflow_sdk.models import ConnectorPublishRequestModel
 
client.connector.publish(ConnectorPublishRequestModel(topic="topic_1", data={"hello": "world"}))

Installation

bash
pip install careflow-sdk

Requirements: 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:

python
from careflow_sdk import CareflowClient
 
client = CareflowClient()

To override URLs, credentials, mTLS certificates, or other settings, pass a ClientOptions value to the constructor:

python
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 .env file: the SDK reads process environment variables only; it does not parse .env files. If you keep config in a .env, load it into the environment yourself before constructing the client (e.g. python-dotenv's load_dotenv(), set -a; source .env, or docker-compose's env_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:

  • app
  • connector
  • streaming
  • pipeline

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:

python
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:

python
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:

python
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.

python
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

python
def get_deployment(
    request_model: GetDeploymentRequestModel | None = None
) -> ResponseModel[DeploymentData]

Retrieve deployment metadata.

Maps to: GET /api/v1/deployment

Deprecated: client.app.publish, subscribe and flush will be removed in a future major version. Use the client.connector equivalents instead. They now call the connector service, so they need connector_base_url, connector_secret and the mTLS settings, and require_signing has no effect. Each emits a DeprecationWarning and logs one WARNING per client on the careflow_sdk logger on first use. Return types are unchanged, but subscribe now returns one connector page per call instead of every waiting record.

publish

python
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".

python
from careflow_sdk.models import AppPublishRequestModel
 
client.app.publish(AppPublishRequestModel(
    topic="output_topic",
    data={"resourceType": "Patient", "id": "test-patient-001"},
))

subscribe

python
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).

python
from careflow_sdk.models import AppSubscribeRequestModel
 
resp = client.app.subscribe(AppSubscribeRequestModel(topic="input_topic"))

flush

python
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

python
from careflow_sdk.models import AppFlushRequestModel
 
client.app.flush(AppFlushRequestModel(topic="input_topic"))

get_users

python
def get_users(request_model: GetUsersRequestModel | None = None) -> ResponseModel[UsersData]

Retrieve App users.

Maps to: GET /api/v1/users

python
from careflow_sdk.models import GetUsersRequestModel
 
resp = client.app.get_users(GetUsersRequestModel())

request_patients

python
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

python
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

python
def get_session(request_model: GetSessionRequestModel) -> ResponseModel[SessionData]

Validate and retrieve session information for an App user session.

Maps to: GET /api/v1/session

python
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)

python
def publish(request_model: ConnectorPublishRequestModel) -> ResponseModel[PublishResult]

Publish records to a connector topic.

Maps to: POST /data-stream/publish

python
from careflow_sdk.models import ConnectorPublishRequestModel
 
client.connector.publish(ConnectorPublishRequestModel(
    topic="output_topic",
    data={"resourceType": "Patient", "id": "test-patient-001", "active": True},
))

subscribe (Connector)

python
def subscribe(request_model: ConnectorSubscribeRequestModel) -> ResponseModel[SubscribeResult]

Fetch records from a connector topic.

Maps to: GET /data-stream/subscribe

python
from careflow_sdk.models import ConnectorSubscribeRequestModel
 
resp = client.connector.subscribe(ConnectorSubscribeRequestModel(topic="input_topic"))

flush (Connector)

python
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

python
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

python
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

python
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 dict

The 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:

python
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:

python
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:

python
result = await async_client.pipeline.execute(command=PipelineCommand.DEPLOYMENT_GET)

Command parameters

CommandParameters
pipeline.deployment.getNone. Returns the app's pipelines under result.deployment_pipelines.models.
pipeline.deployment.listNot implemented on the controller yet; returns NOT_IMPLEMENTED.
pipeline.deployment.statusdeployment_instance_uuid
pipeline.artifact.getdeployment_instance_uuid, config_file (a name from deployment.status's artifact_files). The file comes back base64-encoded in result.content.
pipeline.run.startdeployment_instance_uuid, optional params (pipeline parameters, at most 64 KiB as JSON). Returns the run's deployment_instance_run_uuid.
pipeline.run.statusdeployment_instance_uuid, deployment_instance_run_uuid
pipeline.run.stopdeployment_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:

python
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"):
        break

To 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

StatusMeaning
pendingThe start was accepted and the run is recorded.
startingThe run is being launched.
runningThe pipeline is executing.
completedThe pipeline finished successfully. Final.
failedThe pipeline could not be launched or finished with an error. Final.
stoppingA stop was requested and the run is shutting down.
stoppedThe 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.status also returns requested_at, started_at and completed_at (Unix seconds, null until reached), exit_code, error_message, engine_run_id, run_name and trace (one object per pipeline task with string values, null until the engine writes one).
  • pipeline.run.stop normally returns stopping. 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.status returns deployment_pipeline, deployment_instance and artifact_files. deployment_instance.status is the pipeline deployment's own status (pending, started or stopped), not a run's. artifact_files[].config_file is the exact, case-sensitive name to pass to pipeline.artifact.get.
  • pipeline.artifact.get returns filename, content_type, size (decoded bytes) and the file base64-encoded in content.

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 code maps to the matching error, for example 404 to CareflowNotFoundError and 500 to CareflowServerError.
  • Authentication codes (MISSING_HEADERS, INVALID_SIGNATURE, EXPIRED_TIMESTAMP, …) map to their specific errors.
  • Other codes, such as INVALID_PARAMETERS, RUN_FAILED, STATUS_FAILED, ARTIFACT_FAILED or UNKNOWN_COMMAND, raise CareflowClientError.

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

python
def connect(
    stream_model: ConnectorStreamModel,
    options: ConnectOptions | None = None,
) -> wsgateway.WSGatewayStream

Open 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).

python
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:

python
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 within close_timeout the connection is force-closed and iteration raises CloseTruncatedError — signalling that some delivered messages went unprocessed.
  • Abrupt — break / stream.aclose() / leaving the async with block. 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.
python
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 finish

Notes:

  • 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 via on_error and 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=True on ConnectorStreamModel.
  • 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

plaintext
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/query

RequestModel 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-8
  • accept: application/json
  • user-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:

FieldTypeDescription
require_signingboolWhen True, attaches App signing headers to the request. Default is True.

AppPublishRequestModel

Used by: client.app.publish()

Constructor fields:

FieldTypeDescription
topicstr | NoneTarget topic.
dataAny | NonePayload sent (JSON-encoded) as the data field of the request body.
require_signingboolNo effect: the request goes to the connector service, which does not use App signing.

AppSubscribeRequestModel

Used by: client.app.subscribe()

Constructor fields:

FieldTypeDescription
topicstr | NoneTarget topic. Sent as a query parameter.
require_signingboolNo 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:

FieldTypeDescription
topicstr | NoneTarget topic. Sent as a query parameter.
require_signingboolNo effect: the request goes to the connector service, which does not use App signing.

GetUsersRequestModel

Used by: client.app.get_users()

Constructor fields:

FieldTypeDescription
require_signingboolWhen True, attaches App signing headers to the request. Default is True.

GetSessionRequestModel

Used by: client.app.get_session()

Constructor fields:

FieldTypeDescription
session_tokenstr | NoneSession token to validate. Sent as a query parameter.
require_signingboolWhen True, attaches App signing headers to the request. Default is True.

PatientsRequestModel

Used by: client.app.request_patients()

Constructor fields:

FieldTypeDescription
require_signingboolWhen 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:

FieldTypeDescription
topicstr | NoneTarget topic.
dataAny | NonePayload sent (JSON-encoded) as the data field of the request body.
connector_secretstr | NoneOptional connector secret override. If omitted, the SDK uses ClientOptions.connector_secret.

ConnectorSubscribeRequestModel

Used by: client.connector.subscribe()

Constructor fields:

FieldTypeDescription
topicstr | NoneTarget topic. Sent as a query parameter.
connector_secretstr | NoneOptional connector secret override. If omitted, the SDK uses ClientOptions.connector_secret.

ConnectorFlushRequestModel

Used by: client.connector.flush(). Sends seekToLatest=true automatically.

Constructor fields:

FieldTypeDescription
topicstr | NoneTarget topic. Sent as a query parameter.
connector_secretstr | NoneOptional 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:

FieldTypeDescription
commandstrPipeline 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.
parametersdict | NoneCommand parameters sent as the parameters field of the JSON request body. Defaults to an empty dict when omitted.
require_signingboolWhen 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:

FieldTypeDescription
topicslist[str]One or more topics to subscribe to.
seek_to_latestboolWhen 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:

FieldTypeDescription
reconnect_enabledbool | NoneWhether to automatically reconnect on disconnect. Gateway default True.
reconnect_intervalfloat | NoneInitial delay between reconnect attempts (s). Gateway default 1.0.
reconnect_max_intervalfloat | NoneMaximum delay between reconnect attempts (s). Gateway default 30.0.
reconnect_max_attemptsint | NoneMaximum reconnect attempts before raising. Gateway default unlimited (0).
connection_timeoutfloat | NoneTimeout for establishing the WebSocket connection (s). Gateway default 10.0.
auth_timeoutfloat | NoneTimeout for completing the authentication handshake (s). Gateway default 5.0.
max_queue_sizeint | NoneMessages buffered ahead of a slow consumer before backpressure is applied (0 = unbounded, nothing dropped). Gateway default 32.
close_timeoutfloat | NoneSeconds a graceful close() waits to finish draining before force-closing (raising CloseTruncatedError). Gateway default 30.0.
keepalive_intervalfloat | NoneInterval between WebSocket keep-alive frames on idle connections (0 = disabled). Gateway default 15.0.
keepalive_timeoutfloat | NoneSeconds to wait for a pong before treating the connection as dead and reconnecting. Gateway default 20.0.
on_connectCallable | NoneCalled when the connection is established and authenticated.
on_disconnectCallable | NoneCalled when the connection closes.
on_reconnectCallable | NoneCalled before each reconnect attempt, with (attempt, backoff).
on_errorCallable | NoneCalled 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:

python
ResponseModel[T]

Which contains:

FieldTypeDescription
status_codeintThe HTTP status code of the response.
bodyTThe deserialized, typed response payload.

App response payload models:

  • DeploymentData
  • AppPublishResult
  • AppSubscribeResult
  • UsersData
  • SessionData
  • PatientsRequestResult

Connector response payload models:

  • PublishResult
  • SubscribeResult

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) contains status: str | None ("success").
  • AppSubscribeResult (subscribe, flush) contains data: Any | None, a list of each record's message (or the record itself when it has none).
  • UsersData contains app_users: list[AppUser] | None.
  • SessionData contains user: SessionUserEntry | None.
  • PatientsRequestResult contains topics: list[PatientTopic] | None.
  • PublishResult contains id and topic.
  • SubscribeResult contains data_set_meta, records, and total. DataSetMeta → name, data_type, description, created_time, last_modified_time. SubscribeRecord → key, offset, partition, timestamp, topic, message (Any, the user-defined payload).
  • DeploymentData contains deployment_yaml: DeploymentYaml | None, whose models[].artifacts[] each expose a storages: list[DeploymentStorage] | None with 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 are StrEnums, so they compare equal to their lowercase value (storage.database_type == "mongodb"); unrecognised values parse as UNKNOWN. See Deployment Storage for using storages from an app.

Streaming messages:

  • wsgateway.WsMessage (imported from wsgateway, not careflow_sdk — a frozen dataclass mirroring the .NET Careflow.WsGateway.Models.WsMessage record).
FieldTypeDescription
topicstr | NoneThe topic the message was received from.
keystr | NoneThe message key, used for partitioning and ordering.
valueAnyThe message payload.
partitionintThe partition the message was consumed from. Default 0.
offsetintThe position of the message within its partition. Default 0.
timestampintUnix 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-uuid
  • x-timestamp
  • x-signature

The signing headers are generated from:

  • client_id
  • client_secret
  • HTTP method
  • Relative request path
  • Serialized request body

Canonical string format:

plaintext
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:

  • GetDeploymentRequestModel
  • GetUsersRequestModel
  • GetSessionRequestModel
  • PatientsRequestModel
  • careflow_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.

plaintext
CareflowError
├── CareflowIOError
│   └── CareflowSslError
├── CareflowInvalidDataError
└── CareflowApiError
    ├── CareflowClientError
    │   ├── CareflowBadRequestError
    │   │   └── CareflowValidationError
    │   ├── CareflowUnauthorizedError
    │   ├── CareflowForbiddenError
    │   ├── CareflowNotFoundError
    │   ├── CareflowRateLimitError
    │   ├── CareflowMissingHeadersError
    │   ├── CareflowInvalidTimestampError
    │   ├── CareflowExpiredTimestampError
    │   ├── CareflowInvalidSignatureError
    │   └── CareflowUnknownAppIdError
    ├── CareflowServerError
    │   └── CareflowAuthInternalError
    ├── CareflowMissingProjectError
    ├── CareflowMissingPatientListError
    └── CareflowUnexpectedStatusCodeError

Every 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 → CareflowBadRequestError
  • 401 → CareflowUnauthorizedError
  • 403 → CareflowForbiddenError
  • 404 → CareflowNotFoundError
  • 429 → CareflowRateLimitError
  • 611 → CareflowMissingProjectError
  • 612 → CareflowMissingPatientListError
  • Other 4xx → CareflowClientError
  • 5xx → CareflowServerError

Structured error-code mappings include:

  • MISSING_HEADERS → CareflowMissingHeadersError
  • INVALID_TIMESTAMP → CareflowInvalidTimestampError
  • EXPIRED_TIMESTAMP → CareflowExpiredTimestampError
  • INVALID_SIGNATURE → CareflowInvalidSignatureError
  • UNKNOWN_APP_ID → CareflowUnknownAppIdError
  • AUTH_INTERNAL_ERROR → CareflowAuthInternalError
  • FORBIDDEN → CareflowForbiddenError
  • BAD_REQUEST → CareflowBadRequestError
  • A responseStatus.message field-validation array → CareflowValidationError — exposes .field_errors, where each FieldError has .param and .message
  • 611 → CareflowMissingProjectError — raised by request_patients when no project is assigned to the App.
  • 612 → CareflowMissingPatientListError — raised by request_patients when a project is assigned but no patient list is configured.

Transport or configuration errors may also surface as:

  • CareflowSslError
  • CareflowIOError
  • CareflowInvalidDataError

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:

plaintext
wsgateway.WSGatewayError
├── ConnectionError
├── AuthenticationError
│   ├── InvalidTopicError
│   └── ClientAlreadyConnectedError
├── ReconnectExhaustedError
└── CloseTruncatedError
  • wsgateway.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 hit reconnect_max_attempts.
  • CloseTruncatedError → a graceful close() could not drain within close_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:

  • 429
  • 500
  • 502
  • 503
  • 504
  • I/O failures

A response x-should-retry header (true/false) overrides the status-based decision.

When present, the SDK honors:

  • Retry-After
  • Retry-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

python
def verify_signature(payload: bytes, signature_header: str, secret: str) -> bool

Verify 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.

python
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

python
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())