Patient Context

Patient Context

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

ParameterTypeDescription
external_idstringYour system's unique identifier for this patient
patient_groupstringThe ID of the patient group this patient belongs to

Optional Parameters

ParameterTypeDescription
namestringPatient's full name
birth_datestringPatient's birth date in YYYY-MM-DD format
genderstringPatient's gender: malefemale, 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_at": "2024-01-15T10:30:00Z",
"updated_at": "2024-01-15T10:30:00Z"
}

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",
"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
}

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.

tipp

For complete details on PIS integration and authentication flows, see the PIS Integration documentation.

URL Structure

Parameters

ParameterRequiredDescription
emailYesUser's email address for authentication
integrationYesYour integration ID provided by Haidy
unique_idYesUnique identifier tying the record to your system (typically the patient's external_id)
passwordNoUser's password (if using password authentication)
metadataNoURL-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

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
    • Popular Articles

    • Funktionen

      Funktionen Konsultationsübersicht In der Konsultationsübersicht, sehen Sie alle Konsultationen die geplant, in Bearbeitung oder bereits abgeschlossen sind. Sie können Konsultationen entsprechend filtern oder nach ihnen suchen. Starten Sie eine ...
    • Patienten

      Patienten info Für den Zugriff auf eine Patientengruppe benötigen Sie die entsprechende Berechtigung. Für die Aufnahme in eine entsprechende Gruppe müssen Sie sich an den Admin Ihrer Institution wenden. Wollen Sie Ihre persönliche Patientengruppe ...
    • Registrierung

      Registrierung Eine Anmeldung ist mit jeder gängigen E-Mail Adresse möglich. Folgen Sie den nächsten Schritten, um ein Konto zu erstellen und sich anzumelden. info Verwenden Sie Ihre HIN-Adresse, um den Secure-Mail-Transfer zu nutzen. Besuchen Sie ...
    • Einstellungen

      Einstellungen Konto Mit einem Klick auf “Einstellungen” im Feld unten links, gelangen Sie zu Ihren Kontoeinstellungen. Hier können Sie die Standardeinstellungen bezüglich Sprache, Glossar sowie bezüglich Notizen- und Berichtsvorlage anpassen. ...
    • API Overview

      API Overview Welcome to the Haidy API documentation. Our API suite enables you to integrate powerful medical audio and document processing capabilities into your healthcare applications and workflows. What is the Haidy API? The Haidy API provides a ...