Using the Python SDK
Last Updated: October 14, 2026
This guide walks you through creating a Python application using the Careflow SDK, packaging it as a Docker image, and preparing it for deployment as an embedded application on the Careflow platform.
It covers:
- Project setup
- SDK integration
- Configuration
- Usage
- Dockerization
- Deployment
The end result is a working Docker image ready for Careflow deployment.
1. Prerequisites
Before you start, ensure you have:
- Python 3.11 or newer
- Docker
You will also need the following for local development testing:
- Careflow Azure DevOps PAT
- Application Client ID
- Application Client Secret
- Connector Secret
- App Server base URL
- Connector base URL
- WS Gateway base URL
These environment variables will be automatically set once the application is deployed on Careflow, and will not need to be manually set.
The PAT and secret will be provided on request, as an application needs to be initially created to generate them. Secrets are not publicly exposed and require a system admin to provide if needed for local development testing.
2. Create the Project
Open a terminal and run:
mkdir my-careflow-app
cd my-careflow-app
python3 -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activateYour project structure should look like:
my-careflow-app/
├── pyproject.toml
├── pip.ini
└── src/
└── my_careflow_app/3. Configure the Azure Artifacts Feed
The SDK depends on careflow-wsgateway-client, published (alongside careflow-sdk itself, if you install from the private feed) to a private Azure Artifacts feed. Create a file named pip.ini (pip.conf on macOS/Linux) at the root:
[global]
extra-index-url = https://build:{PYPI_CAREFLOW_PAT}@pkgs.dev.azure.com/careflowhealth/Careflow/_packaging/Careflow/pypi/simple/Replace {PYPI_CAREFLOW_PAT} with your PAT (this is currently provisioned on a request basis). extra-index-url keeps PyPI as the primary source, so public dependencies still resolve normally while the Careflow packages come from Azure.
Per-OS locations for this file:
~/.config/pip/pip.conf # macOS/Linux, per-user (recommended)
$VIRTUAL_ENV/pip.conf # this virtualenv only
%APPDATA%\pip\pip.ini # Windows, per-user (recommended)4. Install the SDK
pip install careflow-sdkRequirements: Python 3.11+.
5. Register the Client
Create your client once and reuse it (e.g. as a FastAPI dependency or module-level singleton):
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",
timeout=30.0,
max_retry=3,
verify_ssl=True,
)
client = CareflowClient(options)Or construct it with no arguments to resolve everything from environment variables:
from careflow_sdk import CareflowClient
client = CareflowClient()For asyncio applications (e.g. FastAPI async routes), use AsyncCareflowClient instead — it takes the same ClientOptions and mirrors every method as async/await:
from careflow_sdk import AsyncCareflowClient
client = AsyncCareflowClient()6. Configure X-Forwarded-Prefix
When the app is hosted behind the Careflow proxy, requests may include an X-Forwarded-Prefix header. If your framework generates absolute URLs or relies on the request path (e.g. redirects, static file links), honor this header so routes resolve correctly when the app is mounted under a subpath instead of /. In a FastAPI/Starlette app, this can be done with middleware that rewrites request.scope["root_path"] from the header before the request is routed.
7. Configure Environment Variables
For local development, the SDK reads its configuration from ClientOptions — either the values you assign directly (as in Section 5) or the CAREFLOW_SDK_* environment variables listed below. The SDK reads process environment variables only; it does not parse .env files on its own — load one into the environment yourself first (e.g. python-dotenv's load_dotenv(), set -a; source .env, or docker-compose's env_file:).
Available expected environment variables
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 (required for publish, subscribe and streaming)
(Optional)
CAREFLOW_SDK_CLIENT_CERT_PATH
CAREFLOW_SDK_CLIENT_KEY_PATH
CAREFLOW_SDK_CA_BUNDLE_PATH
CAREFLOW_SDK_TIMEOUT
CAREFLOW_SDK_MAX_RETRY_COUNT
CAREFLOW_SDK_VERIFY_SSL
Note: These environment variables are already injected by Careflow by default, app developers using the SDK do not need to specify these in their uploaded .env configuration files.
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).
8. Authentication (HMAC)
Each signed request includes:
x-app-uuid
x-timestamp
x-signature
Signature format:
METHOD
PATH
TIMESTAMP
SHA256(body)
No Bearer tokens required. Fully handled by the SDK. App and Pipeline requests are signed by default — pass require_signing=False on the request model to send one unsigned.
9. Using the App API (client.app)
Get Deployment
from careflow_sdk.models import GetDeploymentRequestModel
resp = client.app.get_deployment(GetDeploymentRequestModel())Retrieve deployment metadata. This is an essential API providing all necessary deployment details used for interacting with topics, and other parts of the App deployment.
Maps to: GET /api/v1/deployment
Example response payload:
{
"status": "ok",
"data": {
"deployment_yaml": {
"models": [
{
"name": "app-name-123",
"model": "sample-app",
"artifacts": [
{
"tag": "organization/app-image-name:latest",
"label": "test",
"topics": {
"in": [
{ "topic": "patient-input" }
],
"out": "results-output"
},
"artifact_id": 47,
"configuration": { ... },
"instance_type": "t3.small",
"root_disk_size": "50Gi",
"deployment_instance_id": "33",
"deployment_instance_uuid": "c6bf477b-a701-4171-834c-7fc1033deb43"
}
],
"version": "1.0.0",
"model_id": 12,
"version_id": 37,
"deployment_model_id": "33"
}
],
"topics": [
{
"name": "patient-input",
"type": "JSON",
"topic": "patient-input",
"display": "Patient Input",
"dataset_id": 26
},
{
"name": "results-output",
"type": "JSON",
"topic": "my-project_results-output_3dba02ccc9760ba0",
"display": "Results Output",
"dataset_id": 28
}
],
"project": {
"name": "my-project",
"key_name": "my-project",
"description": "My project description",
"deploy_cluster": false,
"stakeholder_id": 1
},
"deployment_package_id": 23
}
}
}Understanding topic references:
The topics.in and topics.out values inside each image entry are reference names, not the actual topic identifiers. To obtain the real topic string to use when publishing or subscribing, look up the reference name in the top-level topics array by matching the name field.
# 1. Fetch the deployment once and cache it.
deployment = client.app.get_deployment(GetDeploymentRequestModel())
topics = deployment.body.deployment_yaml.topics
# 2. Find the resolved topic by its reference name.
out_topic = next(t.topic for t in topics if t.name == "results-output")
# out_topic == "my-project_results-output_3dba02ccc9760ba0"
# 3. Use the resolved topic when publishing.
from careflow_sdk.models import ConnectorPublishRequestModel
client.connector.publish(ConnectorPublishRequestModel(
topic=out_topic,
data={...},
))Deprecated:
client.app.publish,subscribeandflushwill be removed in a future major version. Use the Connector API instead (see Using the Connector API).
Notes:
- App requests are signed by default; set
require_signing=Falseonly to send one unsigned. - HMAC signing is handled automatically.
Streaming (Real-Time)
client.streaming.connect() opens a persistent WebSocket connection to the WsGateway and yields messages as they arrive across one or more topics. Unlike client.connector.subscribe (which polls), streaming is push-based and stays open until you stop iterating or close the stream.
Setup
Streaming requires CAREFLOW_SDK_WS_GATEWAY_BASE_URL and CAREFLOW_SDK_CONNECTOR_SECRET to be set.
Use the resolved topic values from get_deployment (same as publishing):
from careflow_sdk.models import ConnectorStreamModel
deployment = client.app.get_deployment(GetDeploymentRequestModel())
out_topic = next(t for t in deployment.body.deployment_yaml.topics if t.name == "results-output").topic
async with client.streaming.connect(ConnectorStreamModel(topics=[out_topic])) as stream:
async for message in stream:
print(f"[{message.topic}] {message.value}")Multi-Topic
Multiple topics can be subscribed to in a single connection:
async with client.streaming.connect(ConnectorStreamModel(topics=[input_topic, output_topic])) as stream:
async for message in stream:
# message.topic tells you which topic this message came from
...Notes:
- The gateway allows only one active connection per connector secret.
- Reconnect on disconnect is automatic with exponential backoff (configurable via
ConnectOptions). Transient errors are reported viaConnectOptions.on_errorand retried; only authentication rejection, invalid topics, cancellation, and reconnect exhaustion end the stream. - Each reconnect resumes from the latest Kafka offset, not from the beginning.
- Set
seek_to_latest=TrueonConnectorStreamModelto skip the backlog and only receive data published after connecting. - Idle connections are kept alive automatically (
ConnectOptions.keepalive_interval, default 15 seconds) so dead connections are detected and reconnected. - For serving multiple concurrent clients (e.g. SSE endpoints), use a single
connect()connection with a broadcaster pattern rather than opening one connection per client. - Use
stream.close()(and keep iterating) to stop gracefully without dropping already-buffered messages; usebreak/stream.aclose()/ leaving theasync withblock to stop immediately and discard anything still buffered.
Possible Exceptions:
wsgateway.AuthenticationError- authentication rejected by the WsGatewaywsgateway.InvalidTopicError- one or more requested topics are not provisionedwsgateway.ReconnectExhaustedError- max reconnect attempts exceeded
10. Using the Connector API (client.connector)
The connector namespace interacts with the underlying data-stream service, authenticated by connector_secret rather than HMAC signing.
Publish
from careflow_sdk.models import ConnectorPublishRequestModel
client.connector.publish(ConnectorPublishRequestModel(
topic=request.topic,
data=request.payload,
))Subscribe
from careflow_sdk.models import ConnectorSubscribeRequestModel
result = client.connector.subscribe(ConnectorSubscribeRequestModel(topic=topic))11. Using the Pipeline API (client.pipeline)
The Pipeline API dispatches named commands to the broker over a single endpoint. The command is named in the request body rather than by route, so commands the broker adds later work without an SDK release.
from careflow_sdk.models import PipelineCommand
deployment = client.pipeline.execute(command=PipelineCommand.DEPLOYMENT_GET)
models = deployment.body["result"]["deployment_pipelines"]["models"]PipelineCommand lists the commands known today (DEPLOYMENT_GET, DEPLOYMENT_LIST, DEPLOYMENT_STATUS, ARTIFACT_GET, RUN_START, RUN_STATUS, RUN_STOP) for autocomplete only — command accepts any non-empty string. DEPLOYMENT_GET takes no parameters; the others take the deployment_instance_uuid it returns. See Python SDK for each command's parameters and a full run example.
12. Test Locally
export CAREFLOW_SDK_CLIENT_ID="..."
export CAREFLOW_SDK_CLIENT_SECRET="..."
export CAREFLOW_SDK_CONNECTOR_SECRET="..."
python -m my_careflow_appCreate some test endpoints:
curl http://localhost/healthz
curl http://localhost/api/app/deployment13. Dockerfile
Create a file named Dockerfile, update the corresponding fields for your application:
FROM python:3.12-slim AS build
ARG PYPI_CAREFLOW_PAT
WORKDIR /app
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:${PATH}"
COPY pyproject.toml README.md ./
COPY src/ ./src/
RUN pip install --no-cache-dir \
--index-url "https://build:${PYPI_CAREFLOW_PAT}@pkgs.dev.azure.com/careflowhealth/Careflow/_packaging/Careflow/pypi/simple/" \
--extra-index-url https://pypi.org/simple/ \
careflow-sdk \
&& pip install --no-cache-dir .
FROM python:3.12-slim
WORKDIR /app
COPY --from=build /opt/venv /opt/venv
COPY src/ ./src/
ENV PATH="/opt/venv/bin:${PATH}"
EXPOSE 80
CMD ["uvicorn", "src.api:app", "--host", "0.0.0.0", "--port", "80"]14. Build and Run
Build:
docker build \
--build-arg PYPI_CAREFLOW_PAT="$PYPI_CAREFLOW_PAT" \
-t my-careflow-app:local .Run:
docker run -p 80:80 \
-e CAREFLOW_SDK_CLIENT_ID="..." \
-e CAREFLOW_SDK_CLIENT_SECRET="..." \
-e CAREFLOW_SDK_CONNECTOR_SECRET="..." \
my-careflow-app:local15. Push to Registry
docker tag my-careflow-app:local user/my-careflow-app:1.0.0
docker push user/my-careflow-app:1.0.016. Deployment
Have the following on hand when preparing to deploy the embedded application to Careflow:
- Image name and tag for your embedded application image
- Required environment variables in a .env file (if your application has any that are not automatically provided)
- Input / Output / Control topics
Checklist
- No secrets committed
- PAT not included in the image being deployed
- Singleton/shared client configured (and closed via
close()/ context manager on shutdown) /healthzendpoint works- Signed App requests (the SDK default)
- Proper error handling
- Immutable image tags