Patient contexts are the core organizational unit in Haidy's API. They represent individual patients and serve as containers for their medical documents, consultation data, and AI-generated insights.
A patient context allows you to:
POST /v2/patient-contexts/
| Parameter | Type | Description |
|---|---|---|
external_id | string | Your system's unique identifier for this patient |
patient_group | string | The ID of the patient group this patient belongs to |
| Parameter | Type | Description |
|---|---|---|
name | string | Patient's full name |
birth_date | string | Patient's birth date in YYYY-MM-DD format |
gender | string | Patient's gender: male, female, or other |
curl -X POST https://api.44ai.ch/v2/patient-contexts/ \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"external_id": "patient-12345",
"patient_group": "sqmcrfbv6fx4g04",
"name": "John Doe",
"birth_date": "1980-01-01",
"gender": "male"
}'
{
"id": "ctx_abc123def456",
"external_id": "patient-12345",
"patient_group": "sqmcrfbv6fx4g04",
"name": "John Doe",
"birth_date": "1980-01-01",
"gender": "male",
"created_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}
Once you've created a patient context, you can upload medical documents such as lab reports, discharge summaries, or referral letters.
POST /v2/patient-files/upload/{patient_context_id}
patient_context_id (path parameter): The ID of the patient context returned from the creation stepUse multipart/form-data with one or more files attached under the files field.
curl -X POST https://api.44ai.ch/v2/patient-files/upload/ctx_abc123def456 \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-F "files=@/path/to/lab-report.pdf" \
-F "files=@/path/to/discharge-summary.pdf"
{
"uploaded_files": [
{
"id": "file_xyz789",
"filename": "lab-report.pdf",
"size": 245678,
"content_type": "application/pdf"
},
{
"id": "file_xyz790",
"filename": "discharge-summary.pdf",
"size": 512345,
"content_type": "application/pdf"
}
],
"failed_files": [],
"total_uploaded": 2,
"total_failed": 0
}
The Haidy integration URL allows you to deep-link directly into the Haidy web app for a specific patient context. This is useful for seamless integration with your PIS/EHR system.
For complete details on PIS integration and authentication flows, see the PIS Integration documentation.
| Parameter | Required | Description |
|---|---|---|
email | Yes | User's email address for authentication |
integration | Yes | Your integration ID provided by Haidy |
unique_id | Yes | Unique identifier tying the record to your system (typically the patient's external_id) |
password | No | User's password (if using password authentication) |
metadata | No | URL-encoded JSON object containing patient information |
The metadata object can include:
{
"patient_id": "patient-12345",
"patient_first_name": "John",
"patient_last_name": "Doe",
"patient_birth_date": "1980-01-01"
}
Here's a complete working example that creates a patient context, uploads files, and generates an integration URL:
#!/usr/bin/env python3
import os
import json
import pathlib
import requests
from urllib.parse import urlencode
API_BASE = "https://api.44ai.ch"
BEARER = os.getenv("HAIDY_BEARER", "YOUR_API_TOKEN")
# Patient information
PATIENT_EXTERNAL_ID = "patient-12345"
PATIENT_NAME = "John Doe"
PATIENT_BIRTH_DATE = "1980-01-01"
PATIENT_GROUP_ID = "sqmcrfbv6fx4g04"
# Files to upload
FILE_PATHS = [
"/path/to/lab-report.pdf",
"/path/to/discharge-summary.pdf"
]
# Integration details
INTEGRATION_ID = "o10i0iva3tn75kk"
USER_EMAIL = "user@example.com"
USER_PASSWORD = "" # optional
UNIQUE_ID = PATIENT_EXTERNAL_ID
session = requests.Session()
session.headers.update({"Authorization": f"Bearer {BEARER}"})
def create_patient_context():
"""Create a new patient context."""
url = f"{API_BASE}/v2/patient-contexts/"
body = {
"external_id": PATIENT_EXTERNAL_ID,
"patient_group": PATIENT_GROUP_ID,
"name": PATIENT_NAME,
"birth_date": PATIENT_BIRTH_DATE,
}
resp = session.post(url, json=body)
resp.raise_for_status()
data = resp.json()
print(f"✅ Created patient context: {data['id']}")
return data
def upload_files(patient_context_id, file_paths):
"""Upload files to the patient context."""
url = f"{API_BASE}/v2/patient-files/upload/{patient_context_id}"
files = []
opened = []
try:
for path in file_paths:
p = pathlib.Path(path)
if not p.is_file():
print(f"❌ File not found: {path}")
continue
f = open(p, "rb")
opened.append(f)
files.append(("files", (p.name, f, "application/octet-stream")))
if files:
resp = session.post(url, files=files)
resp.raise_for_status()
data = resp.json()
print(f"✅ Uploaded {data['total_uploaded']} file(s)")
return data
finally:
for f in opened:
f.close()
def build_integration_url(email, integration_id, unique_id, password=None, meta=None):
"""Build the Haidy integration URL."""
base = "https://haidy.ch/integration"
params = {
"email": email,
"integration": integration_id,
"unique_id": unique_id,
}
if password:
params["password"] = password
if meta:
params["metadata"] = json.dumps(meta, ensure_ascii=False)
return f"{base}?{urlencode(params)}"
def main():
# 1. Create patient context
ctx = create_patient_context()
patient_context_id = ctx["id"]
# 2. Upload files
upload_files(patient_context_id, FILE_PATHS)
# 3. Generate integration URL
meta = {
"patient_id": PATIENT_EXTERNAL_ID,
"patient_first_name": PATIENT_NAME.split()[0],
"patient_last_name": PATIENT_NAME.split()[-1],
"patient_birth_date": PATIENT_BIRTH_DATE,
}
url = build_integration_url(
email=USER_EMAIL,
password=USER_PASSWORD or None,
integration_id=INTEGRATION_ID,
unique_id=UNIQUE_ID,
meta=meta,
)
print(f"\n🔗 Integration URL:\n{url}")
print(f"\n✨ Patient Context ID: {patient_context_id}")
if __name__ == "__main__":
main()
external_idAlways implement proper error handling:
try:
resp = session.post(url, json=body)
resp.raise_for_status()
data = resp.json()
except requests.exceptions.HTTPError as e:
print(f"HTTP Error: {e.response.status_code}")
print(f"Response: {e.response.text}")
except Exception as e:
print(f"Error: {e}")
If you try to create a patient context with an external_id that already exists in the same patient group, you'll receive a 400 error. Either use a different external ID or retrieve the existing patient context.
Ensure the patient_group ID is valid and belongs to your organization. Contact support if you need help finding your patient group IDs.
If files fail to upload: