Patient Context
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.
Overview
A patient context allows you to:
- Store and manage patient demographic information
- Upload and organize medical documents
- Track patient records across your system using external IDs
- Generate integration URLs for direct access in the Haidy web app
Creating a Patient Context
Endpoint
POST /v2/patient-contexts/
Required Parameters
| 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 |
Optional Parameters
| 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 |
Example Request
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"
}'
Example Response
{
"id": "ctx_abc123def456",
"external_id": "patient-12345",
"patient_group": "sqmcrfbv6fx4g04",
"name": "John Doe",
"birth_date": "1980-01-01",
"gender": "male",
"created": "2024-01-15T10:30:00Z",
"updated": "2024-01-15T10:30:00Z",
"total_files": 0,
"parsed_files": 0,
"overtime_files": 0,
"error_files": 0
}
Uploading Files to a Patient Context
Once you've created a patient context, you can upload medical documents such as lab reports, discharge summaries, or referral letters.
Endpoint
POST /v2/patient-files/upload/{patient_context_id}
Parameters
patient_context_id(path parameter): The ID of the patient context returned from the creation step
Request Format
Use multipart/form-data with one or more files attached under the files field.
Example Request
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"
Example Response
{
"uploaded_files": [
{
"id": "file_xyz789",
"file": "https://api.44ai.ch/api/files/patient_files/file_xyz789/lab-report.pdf",
"patient_context": "ctx_abc123def456",
"uploaded_by": "user_123",
"created": "2024-01-15T10:35:00Z",
"updated": "2024-01-15T10:35:00Z",
"error": null,
"metadata_internal": null,
"file_type": {
"detected_mime_type": "application/pdf",
"modality": "document"
}
},
{
"id": "file_xyz790",
"file": "https://api.44ai.ch/api/files/patient_files/file_xyz790/discharge-summary.pdf",
"patient_context": "ctx_abc123def456",
"uploaded_by": "user_123",
"created": "2024-01-15T10:35:01Z",
"updated": "2024-01-15T10:35:01Z",
"error": null,
"metadata_internal": null,
"file_type": {
"detected_mime_type": "application/pdf",
"modality": "document"
}
}
],
"failed_files": [],
"total_uploaded": 2,
"total_failed": 0
}
Integration URL
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.
URL Structure
https://haidy.ch/integration?email={email}&integration={integration_id}&unique_id={unique_id}&password={password}&metadata={metadata}
Parameters
| 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 |
Metadata Object
The metadata object can include:
{
"patient_id": "patient-12345",
"patient_first_name": "John",
"patient_last_name": "Doe",
"patient_birth_date": "1980-01-01"
}
Example URL
https://haidy.ch/integration?email=user@example.com&integration=o10i0iva3tn75kk&unique_id=patient-12345&metadata=%7B%22patient_id%22%3A%22patient-12345%22%2C%22patient_first_name%22%3A%22John%22%2C%22patient_last_name%22%3A%22Doe%22%2C%22patient_birth_date%22%3A%221980-01-01%22%7D
Complete Python Example
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()
Best Practices
External IDs
- Use your system's unique patient identifier as the
external_id - Ensure external IDs are consistent across all API calls for the same patient
- External IDs should be URL-safe strings
File Uploads
- Supported formats: PDF, DOCX, TXT, JPG, PNG
- Maximum file size: 50MB per file
- Upload multiple files in a single request when possible for better performance
Error Handling
Always 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}")
Common Issues
Duplicate External ID
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.
Invalid Patient Group
Ensure the patient_group ID is valid and belongs to your organization. Contact support if you need help finding your patient group IDs.
File Upload Failures
If files fail to upload:
- Check file size limits (50MB max)
- Verify the file format is supported
- Ensure the patient context exists before uploading files
Next Steps
- Learn about Document Structuring to process uploaded files
- Explore Tasks for AI-powered analysis
- Set up PIS Integration for seamless workflow integration