Sandbox Client
Simplified client for testing healthcare services with various data sources.
This class provides an intuitive interface for: - Loading test datasets (MIMIC-on-FHIR, Synthea) - Generating synthetic FHIR data - Sending requests to healthcare services - Managing request/response lifecycle
Examples:
Load from dataset registry:
>>> client = SandboxClient(
... url="http://localhost:8000/cds/cds-services/my-service"
... )
>>> client.load_from_registry("mimic-on-fhir", sample_size=10)
>>> responses = client.send_requests()
Load CDA file from path:
>>> client = SandboxClient(
... url="http://localhost:8000/notereader/fhir/",
... protocol="soap"
... )
>>> client.load_from_path("./data/clinical_note.xml")
>>> responses = client.send_requests()
Generate data from free text:
>>> client = SandboxClient(
... url="http://localhost:8000/cds/cds-services/discharge-summarizer"
... )
>>> client.load_free_text(
... csv_path="./data/notes.csv",
... column_name="text",
... workflow="encounter-discharge"
... )
>>> responses = client.send_requests()
Source code in healthchain/sandbox/sandboxclient.py
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 | |
__enter__()
__exit__(exc_type, exc_val, exc_tb)
Context manager exit - auto-save results if responses exist.
Only saves if no exception occurred and responses were generated.
Source code in healthchain/sandbox/sandboxclient.py
__init__(url, workflow, protocol='rest', timeout=10.0)
Initialize SandboxClient.
| PARAMETER | DESCRIPTION |
|---|---|
url
|
Full service URL (e.g., "http://localhost:8000/cds/cds-services/my-service")
TYPE:
|
workflow
|
Workflow specification (required) - determines request type and validation
TYPE:
|
protocol
|
Communication protocol - "rest" for CDS Hooks, "soap" for CDA
TYPE:
|
timeout
|
Request timeout in seconds
TYPE:
|
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If url or workflow-protocol combination is invalid |
Source code in healthchain/sandbox/sandboxclient.py
__repr__()
String representation of SandboxClient.
Source code in healthchain/sandbox/sandboxclient.py
clear_requests()
Clear all queued requests.
Useful when you want to start fresh without creating a new client instance.
| RETURNS | DESCRIPTION |
|---|---|
SandboxClient
|
Self for method chaining |
Source code in healthchain/sandbox/sandboxclient.py
get_request_data(format='dict')
Get transformed request data for inspection.
Allows access to serialized request data for debugging or custom processing.
For direct access to Pydantic models, use the requests attribute:
>>> for request in client.requests:
>>> print(request.model_dump())
| PARAMETER | DESCRIPTION |
|---|---|
format
|
Return format - "dict" for list of dictionaries, "json" for JSON string
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Union[List[Dict], str]
|
Request data in specified format |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If format is not "dict" or "json" |
Examples:
>>> client.load_from_path("data.xml")
>>> # Access raw Pydantic models directly
>>> for request in client.requests:
>>> print(request.model_dump(exclude_none=True))
>>> # Get as dictionaries
>>> dicts = client.get_request_data("dict")
>>> # Get as JSON string
>>> json_str = client.get_request_data("json")
>>> print(json_str)
Source code in healthchain/sandbox/sandboxclient.py
get_status()
Get current client status and statistics.
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Dictionary containing client status information |
Source code in healthchain/sandbox/sandboxclient.py
load_free_text(csv_path, column_name, generate_synthetic=True, random_seed=None, **kwargs)
Load free-text notes from a CSV column and create FHIR DocumentReferences for CDS prefetch. Optionally include synthetic FHIR resources based on the current workflow.
| PARAMETER | DESCRIPTION |
|---|---|
csv_path
|
Path to the CSV file
TYPE:
|
column_name
|
Name of the text column
TYPE:
|
generate_synthetic
|
Whether to add synthetic FHIR resources (default: True)
TYPE:
|
random_seed
|
Seed for reproducible results
TYPE:
|
**kwargs
|
Extra parameters for data generation
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SandboxClient
|
self |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If the CSV file does not exist |
ValueError
|
If the column is not found |
Source code in healthchain/sandbox/sandboxclient.py
load_from_path(path, pattern=None)
Load data from a file or directory.
Supports single files or all matching files in a directory (with optional glob pattern). For .xml (SOAP protocol) loads CDA; for .json (REST protocol) loads Prefetch.
| PARAMETER | DESCRIPTION |
|---|---|
path
|
File or directory path.
TYPE:
|
pattern
|
Glob pattern for files in directory (e.g., "*.xml").
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SandboxClient
|
Self. |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If path does not exist. |
ValueError
|
If no matching files are found or if path is not file/dir. |
Source code in healthchain/sandbox/sandboxclient.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | |
load_from_registry(source, data_dir, **kwargs)
Load data from the dataset registry.
Loads pre-configured datasets like MIMIC-on-FHIR, Synthea, or custom registered datasets.
| PARAMETER | DESCRIPTION |
|---|---|
source
|
Dataset name (e.g., "mimic-on-fhir", "synthea")
TYPE:
|
data_dir
|
Path to the dataset directory
TYPE:
|
**kwargs
|
Dataset-specific parameters (e.g., resource_types, sample_size)
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
SandboxClient
|
Self for method chaining |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If dataset not found in registry |
FileNotFoundError
|
If data_dir doesn't exist |
Examples:
Load MIMIC dataset:
>>> client = SandboxClient(
... url="http://localhost:8000/cds/patient-view",
... workflow="patient-view",
... )
>>> client.load_from_registry(
... "mimic-on-fhir",
... data_dir="./data/mimic-fhir",
... resource_types=["MimicMedication"],
... sample_size=10
... )
Source code in healthchain/sandbox/sandboxclient.py
preview_requests(limit=None)
Get preview of queued requests without sending them.
Provides a summary view of what requests are queued, useful for debugging and verifying data was loaded correctly before sending.
| PARAMETER | DESCRIPTION |
|---|---|
limit
|
Maximum number of requests to preview. If None, preview all.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[Dict[str, Any]]
|
List of request summary dictionaries containing metadata |
Source code in healthchain/sandbox/sandboxclient.py
save_results(directory='./output/')
Save request and response data to disk.
| PARAMETER | DESCRIPTION |
|---|---|
directory
|
Directory to save data to (default: "./output/")
TYPE:
|
Source code in healthchain/sandbox/sandboxclient.py
send_requests()
Send all queued requests to the service.
| RETURNS | DESCRIPTION |
|---|---|
List[Dict]
|
List of response dictionaries |
Source code in healthchain/sandbox/sandboxclient.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
CdsDataGenerator
Generates synthetic CDS (Clinical Decision Support) data for specified workflows.
Uses registered generators to create FHIR resources (e.g., Patient, Encounter, Condition) according to workflow configuration. Can optionally include free text data from a CSV file as DocumentReference.
| ATTRIBUTE | DESCRIPTION |
|---|---|
registry |
Maps generator names to classes.
TYPE:
|
mappings |
Maps workflows to required generators.
TYPE:
|
generated_data |
Most recently generated resources.
TYPE:
|
workflow |
Currently active workflow.
TYPE:
|
Example
generator = CdsDataGenerator() generator.set_workflow("encounter_discharge") data = generator.generate_prefetch(random_seed=42)
Source code in healthchain/sandbox/generators/cdsdatagenerator.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
fetch_generator(generator_name)
Return the generator class by name from the registry.
| PARAMETER | DESCRIPTION |
|---|---|
generator_name
|
Name of the data generator.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Callable
|
Generator class, or None if not found.
TYPE:
|
Example
gen = CdsDataGenerator().fetch_generator("PatientGenerator")
Source code in healthchain/sandbox/generators/cdsdatagenerator.py
free_text_parser(path_to_csv, column_name)
Read a column of free text from a CSV file.
| PARAMETER | DESCRIPTION |
|---|---|
path_to_csv
|
Path to CSV file.
TYPE:
|
column_name
|
Column name to extract.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[str]
|
List[str]: Extracted text values. |
| RAISES | DESCRIPTION |
|---|---|
FileNotFoundError
|
If CSV file does not exist. |
ValueError
|
If column_name is not provided. |
Source code in healthchain/sandbox/generators/cdsdatagenerator.py
generate_prefetch(constraints=None, free_text_path=None, column_name=None, random_seed=None, generate_resources=True)
Generate prefetch FHIR resources and/or DocumentReference.
| PARAMETER | DESCRIPTION |
|---|---|
constraints
|
Constraints for resource generation.
TYPE:
|
free_text_path
|
CSV file containing free text.
TYPE:
|
column_name
|
CSV column for free text.
TYPE:
|
random_seed
|
Random seed.
TYPE:
|
generate_resources
|
If True, generate synthetic FHIR resources.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Resource]
|
Dict[str, Resource]: Generated resources keyed by resource type (lowercase), plus "document" if a free text entry is used. |
| RAISES | DESCRIPTION |
|---|---|
ValueError
|
If workflow is not recognized, or column name is missing. |
FileNotFoundError
|
If free_text_path does not exist. |
Source code in healthchain/sandbox/generators/cdsdatagenerator.py
set_workflow(workflow)
Set the current workflow name to use for data generation.
| PARAMETER | DESCRIPTION |
|---|---|
workflow
|
Workflow name.
TYPE:
|
CDSRequest
Bases: BaseModel
A model representing the data structure for a CDS service call, triggered by specific hooks within a healthcare application.
| ATTRIBUTE | DESCRIPTION |
|---|---|
hook |
The hook that triggered this CDS Service call. For example, 'patient-view'.
TYPE:
|
hookInstance |
A universally unique identifier for this particular hook call.
TYPE:
|
fhirServer |
The base URL of the CDS Client's FHIR server. This field is required if
TYPE:
|
fhirAuthorization |
Optional authorization details providing a bearer access token for FHIR resources.
TYPE:
|
context |
Hook-specific contextual data required by the CDS service.
TYPE:
|
prefetch |
Optional FHIR data that was prefetched by the CDS Client.
TYPE:
|
Documentation: https://cds-hooks.org/specification/current/#http-request_1
Source code in healthchain/models/requests/cdsrequest.py
model_dump(**kwargs)
Model dump method to convert any nested datetime and byte objects to strings for readability. This is also a workaround to this Pydantic V2 issue https://github.com/pydantic/pydantic/issues/9571 For proper JSON serialization, should use model_dump_json() instead when issue is resolved.
Source code in healthchain/models/requests/cdsrequest.py
Action
Bases: BaseModel
Within a suggestion, all actions are logically AND'd together, such that a user selecting a suggestion selects all of the actions within it. When a suggestion contains multiple actions, the actions SHOULD be processed as per FHIR's rules for processing transactions with the CDS Client's fhirServer as the base url for the inferred full URL of the transaction bundle entries.
https://cds-hooks.org/specification/current/#action
Source code in healthchain/models/responses/cdsresponse.py
ActionTypeEnum
CDSResponse
Bases: BaseModel
Represents the response from a CDS service.
This class models the structure of a CDS Hooks response, which includes cards for displaying information or suggestions to the user, and optional system actions that can be executed automatically.
| ATTRIBUTE | DESCRIPTION |
|---|---|
cards |
A list of Card objects to be displayed to the end user. Default is an empty list.
TYPE:
|
systemActions |
A list of Action objects representing actions that the CDS Client should execute as part of performing the decision support requested. This field is optional.
TYPE:
|
For more information, see: https://cds-hooks.org/specification/current/#cds-service-response
Source code in healthchain/models/responses/cdsresponse.py
Card
Bases: BaseModel
Cards can provide a combination of information (for reading), suggested actions (to be applied if a user selects them), and links (to launch an app if the user selects them). The CDS Client decides how to display cards, but this specification recommends displaying suggestions using buttons, and links using underlined text.
https://cds-hooks.org/specification/current/#card-attributes
Source code in healthchain/models/responses/cdsresponse.py
IndicatorEnum
Bases: str, Enum
Urgency/importance of what Card conveys. Allowed values, in order of increasing urgency, are: info, warning, critical. The CDS Client MAY use this field to help make UI display decisions such as sort order or coloring.
Source code in healthchain/models/responses/cdsresponse.py
Link
Bases: BaseModel
-
CDS Client support for appContext requires additional coordination with the authorization server that is not described or specified in CDS Hooks nor SMART.
-
Autolaunchable is experimental
https://cds-hooks.org/specification/current/#link
Source code in healthchain/models/responses/cdsresponse.py
LinkTypeEnum
Bases: str, Enum
The type of the given URL. There are two possible values for this field. A type of absolute indicates that the URL is absolute and should be treated as-is. A type of smart indicates that the URL is a SMART app launch URL and the CDS Client should ensure the SMART app launch URL is populated with the appropriate SMART launch parameters.
Source code in healthchain/models/responses/cdsresponse.py
SelectionBehaviorEnum
Bases: str, Enum
Describes the intended selection behavior of the suggestions in the card. Allowed values are: at-most-one, indicating that the user may choose none or at most one of the suggestions; any, indicating that the end user may choose any number of suggestions including none of them and all of them. CDS Clients that do not understand the value MUST treat the card as an error.
Source code in healthchain/models/responses/cdsresponse.py
SimpleCoding
Bases: BaseModel
The Coding data type captures the concept of a code. This coding type is a standalone data type in CDS Hooks modeled after a trimmed down version of the FHIR Coding data type.
Source code in healthchain/models/responses/cdsresponse.py
Source
Bases: BaseModel
Grouping structure for the Source of the information displayed on this card. The source should be the primary source of guidance for the decision support Card represents.
https://cds-hooks.org/specification/current/#source
Source code in healthchain/models/responses/cdsresponse.py
Suggestion
Bases: BaseModel
Allows a service to suggest a set of changes in the context of the current activity (e.g. changing the dose of a medication currently being prescribed, for the order-sign activity). If suggestions are present, selectionBehavior MUST also be provided.
https://cds-hooks.org/specification/current/#suggestion
Source code in healthchain/models/responses/cdsresponse.py
CdaRequest
Bases: BaseModel
Source code in healthchain/models/requests/cdarequest.py
from_dict(data)
classmethod
model_dump(*args, **kwargs)
model_dump_xml(*args, **kwargs)
Decodes and dumps document as an xml string
Source code in healthchain/models/requests/cdarequest.py
CdaResponse
Bases: BaseModel
Source code in healthchain/models/responses/cdaresponse.py
from_dict(data)
classmethod
model_dump(*args, **kwargs)
model_dump_xml(*args, **kwargs)
Decodes and dumps document as an xml string