Example 1: Simple diabetes case
Use case
Process a clinical note about a diabetes patient and extract ICD-10 codes with confidence scores.Input text
Patient presents with Type 2 Diabetes Mellitus. Currently on Metformin 500mg BID and Glipizide 5mg QD. Blood glucose levels stable at 120-140 mg/dL fasting. No complications noted. Patient reports good compliance with medications and diet. HbA1c: 6.8%. No diabetic retinopathy, nephropathy, or neuropathy.
Complete request
import requests
url = "https://{your-endpoint}/v1/codify"
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"Content-Type": "application/json",
"x-doctor": "dr_123",
"x-patient": "pt_456"
}
payload = {
"medical_note": "Patient presents with Type 2 Diabetes Mellitus. Currently on Metformin 500mg BID and Glipizide 5mg QD. Blood glucose levels stable at 120-140 mg/dL fasting. No complications noted. Patient reports good compliance with medications and diet. HbA1c: 6.8%. No diabetic retinopathy, nephropathy, or neuropathy.",
"model": "balanced"
}
response = requests.post(url, json=payload, headers=headers)
result = response.json()
print(f"Final codes: {len(result['final_code_assessments'])}")
for assessment in result['final_code_assessments']:
print(f" {assessment['code']}: {assessment['description']}")
print(f" Confidence: {assessment['confidence_percent']}%")
print(f" Justification: {assessment['justification']}\n")
print(f"Run ID: {result['run_id']}")
Response
{
"final_code_assessments": [
{
"code": "E11.9",
"description": "Type 2 diabetes mellitus without complications",
"justification": "The note documents Type 2 Diabetes without mention of decompensation or complications; corresponds to E11.9 (DM2 without complications). The stable blood glucose levels and HbA1c of 6.8% indicate controlled diabetes with no evidence of complications.",
"confidence_percent": 95.2
},
{
"code": "Z79.84",
"description": "Long term (current) use of oral hypoglycemic drugs",
"justification": "The patient uses metformin and glipizide chronically; both are oral antidiabetic drugs, supporting long term use of oral hypoglycemic drugs.",
"confidence_percent": 98.1
}
],
"discarded_code_assessments": [
{
"code": "E11.65",
"description": "Type 2 diabetes mellitus with hyperglycemia",
"justification": "Discarded because blood glucose levels are stable and controlled (120-140 mg/dL fasting), not indicating hyperglycemia.",
"confidence_percent": 12.3
}
],
"run_id": "1ef8e0d4-7890-6b3c-8f90-abcdef123456"
}
- E11.9: Type 2 diabetes mellitus without complications (95.2% confidence)
- Z79.84: Long term use of oral hypoglycemic drugs (98.1% confidence)
- The AI correctly identified controlled diabetes and discarded hyperglycemia code due to stable glucose levels
Example 2: Emergency pneumonia case
Use case
Process an emergency department note for a patient with pneumonia and extract ICD-10 codes.Input text
45-year-old male patient presents to emergency department with fever up to 39°C, productive cough, and shortness of breath for 3 days. Physical examination reveals decreased breath sounds and crackles in right lower lobe. Vital signs: BP 130/85, HR 98, RR 22, SpO2 94% on room air. Chest X-ray shows right lower lobe infiltrate consistent with lobar pneumonia. Diagnosis: Community-acquired pneumonia, right lower lobe. Started on IV ceftriaxone 1g and azithromycin 500mg. Patient admitted for observation and continued antibiotic therapy.
Complete request
import requests
url = "https://{your-endpoint}/v1/codify"
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"Content-Type": "application/json",
"x-doctor": "dr_emergency_001",
"x-patient": "pt_789"
}
payload = {
"medical_note": "45-year-old male patient presents to emergency department with fever up to 39°C, productive cough, and shortness of breath for 3 days. Physical examination reveals decreased breath sounds and crackles in right lower lobe. Vital signs: BP 130/85, HR 98, RR 22, SpO2 94% on room air. Chest X-ray shows right lower lobe infiltrate consistent with lobar pneumonia. Diagnosis: Community-acquired pneumonia, right lower lobe. Started on IV ceftriaxone 1g and azithromycin 500mg. Patient admitted for observation and continued antibiotic therapy."
}
response = requests.post(url, json=payload, headers=headers)
result = response.json()
# Filter high confidence codes
high_confidence = [
a for a in result['final_code_assessments']
if a['confidence_percent'] >= 90
]
print(f"High confidence codes ({len(high_confidence)}):")
for assessment in high_confidence:
print(f" {assessment['code']}: {assessment['description']} ({assessment['confidence_percent']}%)")
Response
{
"final_code_assessments": [
{
"code": "J18.1",
"description": "Lobar pneumonia, unspecified organism",
"justification": "The chest X-ray confirms right lower lobe infiltrate consistent with lobar pneumonia. The diagnosis explicitly states community-acquired pneumonia affecting the right lower lobe, which corresponds to J18.1.",
"confidence_percent": 96.8
},
{
"code": "R50.9",
"description": "Fever, unspecified",
"justification": "Patient presents with documented fever up to 39°C, which is a significant presenting symptom requiring coding.",
"confidence_percent": 91.5
}
],
"discarded_code_assessments": [
{
"code": "J15.9",
"description": "Bacterial pneumonia, unspecified",
"justification": "While possible, the note doesn't specify bacterial etiology with certainty. J18.1 (lobar pneumonia) is more specific and accurate based on the radiological findings.",
"confidence_percent": 45.2
}
],
"run_id": "2af9f1e5-8901-7c4d-9g01-bcdef234567"
}
- J18.1: Lobar pneumonia (96.8% confidence) - Primary diagnosis
- R50.9: Fever (91.5% confidence) - Significant presenting symptom
- The AI correctly selected lobar pneumonia over unspecified bacterial pneumonia based on radiological evidence
Example 3: PDF file processing
Use case
Process a PDF medical report and extract ICD-10 codes.Complete request with PDF encoding
import requests
import base64
def encode_pdf(file_path):
"""Encode a PDF file to base64"""
with open(file_path, 'rb') as file:
pdf_bytes = file.read()
base64_data = base64.b64encode(pdf_bytes).decode('utf-8')
return {
"type": "file",
"source_type": "base64",
"data": base64_data,
"mime_type": "application/pdf",
"filename": file_path.split('/')[-1]
}
# Encode the PDF
pdf_file = encode_pdf("medical_report_2025.pdf")
url = "https://{your-endpoint}/v1/codify"
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"Content-Type": "application/json",
"x-doctor": "dr_456",
"x-patient": "pt_101"
}
payload = {
"pdf_file": pdf_file,
"model": "high-quality"
}
response = requests.post(url, json=payload, headers=headers)
result = response.json()
print(f"Processed PDF: {pdf_file['filename']}")
print(f"Final codes: {len(result['final_code_assessments'])}")
for assessment in result['final_code_assessments']:
print(f" {assessment['code']}: {assessment['description']} ({assessment['confidence_percent']}%)")
Response
The response format is identical to text input, containingfinal_code_assessments, discarded_code_assessments, and run_id.
Example 4: FHIR bundle extraction
Use case
Process clinical data already structured in FHIR (Fast Healthcare Interoperability Resources) format and extract simplified diagnostic codes or aggregated information.The API can also receive FHIR JSON as input to extract/transform specific information.
Input (FHIR Bundle as JSON)
{
"resourceType": "Bundle",
"type": "collection",
"entry": [
{
"resource": {
"resourceType": "Patient",
"id": "patient-001",
"name": [{ "family": "Garcia", "given": ["Ana", "Maria"] }],
"birthDate": "1978-03-15",
"gender": "female"
}
},
{
"resource": {
"resourceType": "Condition",
"id": "condition-diabetes",
"clinicalStatus": {
"coding": [{ "system": "http://terminology.hl7.org/CodeSystem/condition-clinical", "code": "active" }]
},
"code": {
"coding": [
{ "system": "http://snomed.info/sct", "code": "44054006", "display": "Diabetes mellitus type 2" },
{ "system": "http://hl7.org/fhir/sid/icd-10", "code": "E11.9", "display": "Type 2 diabetes mellitus without complications" }
]
},
"subject": { "reference": "Patient/patient-001" }
}
},
{
"resource": {
"resourceType": "Condition",
"id": "condition-hta",
"clinicalStatus": {
"coding": [{ "system": "http://terminology.hl7.org/CodeSystem/condition-clinical", "code": "active" }]
},
"code": {
"coding": [
{ "system": "http://snomed.info/sct", "code": "38341003", "display": "Hypertensive disorder" },
{ "system": "http://hl7.org/fhir/sid/icd-10", "code": "I10", "display": "Essential hypertension" }
]
},
"subject": { "reference": "Patient/patient-001" }
}
},
{
"resource": {
"resourceType": "Observation",
"id": "obs-glucose",
"status": "final",
"code": {
"coding": [{ "system": "http://loinc.org", "code": "2339-0", "display": "Glucose [Mass/volume] in Blood" }]
},
"subject": { "reference": "Patient/patient-001" },
"effectiveDateTime": "2025-10-19T10:15:00Z",
"valueQuantity": { "value": 185, "unit": "mg/dL", "system": "http://unitsofmeasure.org", "code": "mg/dL" },
"interpretation": [
{ "coding": [{ "system": "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation", "code": "H", "display": "High" }] }
]
}
}
]
}
JSON Schema for summary extraction
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "fhir_extraction/v1",
"type": "object",
"required": ["patient", "active_diagnoses", "relevant_observations"],
"properties": {
"patient": {
"type": "object",
"properties": {
"full_name": { "type": "string" },
"age": { "type": "integer", "description": "Age calculated from birth date" },
"gender": { "type": "string", "enum": ["male", "female", "other"] }
}
},
"active_diagnoses": {
"type": "array",
"description": "Active diagnoses with ICD-10 codes",
"items": {
"type": "object",
"properties": {
"icd10_code": { "type": "string", "source": "CIE-10-MC-ES-2026" },
"description": { "type": "string" }
}
}
},
"relevant_observations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": { "type": "string", "description": "Observation type (lab, vital sign, etc.)" },
"name": { "type": "string" },
"value": { "type": "string" },
"interpretation": { "type": "string", "description": "Normal, High, Low, etc." }
}
}
},
"clinical_summary": { "type": "string", "description": "Narrative summary of the encounter" }
}
}
Request
import json
import requests
fhir_bundle = {
"resourceType": "Bundle",
"type": "collection",
"entry": [
# ... (the complete FHIR bundle from above)
]
}
payload = {
"input": json.dumps(fhir_bundle, ensure_ascii=False),
"json_schema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["patient", "active_diagnoses"],
"properties": {
"patient": {
"type": "object",
"properties": {
"full_name": {"type": "string"},
"age": {"type": "integer"},
"gender": {"type": "string"}
}
},
"active_diagnoses": {
"type": "array",
"items": {
"type": "object",
"properties": {
"icd10_code": {"type": "string", "source": "CIE-10-MC-ES-2026"},
"description": {"type": "string"}
}
}
},
"relevant_observations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {"type": "string"},
"name": {"type": "string"},
"value": {"type": "string"},
"interpretation": {"type": "string"}
}
}
},
"clinical_summary": {"type": "string"}
}
},
"configure": "Extract information from the FHIR bundle and simplify to readable format. Keep ICD-10 codes when available.",
"target_language": "en"
}
response = requests.post(
"https://{your-endpoint}/v1/codify",
json=payload,
headers={
"Authorization": "Bearer YOUR_TOKEN",
"x-doctor": "dr_123",
"x-patient": "pt_001"
}
)
result = response.json()
print(json.dumps(result['data'], indent=2))
Response
{
"data": {
"patient": {
"full_name": "Ana Maria Garcia",
"age": 47,
"gender": "female"
},
"active_diagnoses": [
{ "icd10_code": "E11.9", "description": "Type 2 diabetes mellitus without complications" },
{ "icd10_code": "I10", "description": "Essential (primary) hypertension" }
],
"relevant_observations": [
{ "type": "Laboratory", "name": "Blood glucose", "value": "185 mg/dL", "interpretation": "High" }
],
"clinical_summary": "47-year-old female patient with type 2 diabetes mellitus and essential hypertension in follow-up. Latest blood glucose elevated (185 mg/dL). Requires treatment adjustment."
},
"run_id": "run_fhir_extract_001"
}
- Simplify complex FHIR bundles into readable reports
- Extract specific codes (ICD-10, SNOMED, LOINC) from FHIR resources
- Generate narrative summaries from structured FHIR data
- Convert between FHIR/HL7 versions or normalize codes
Example 5: Structured clinical note extraction
Use case
Extract structured fields from a medical consultation (reason, current illness, treatment plan, vital signs, etc.) for automatic EHR documentation.Complete request
import requests
payload = {
"input": "29-year-old female patient with odynophagia, fever 38.5C for 2 days. Examination: tonsillar plaques, tender cervical lymphadenopathy, no rash. Treatment: ibuprofen and rest. Antigen test suggested.",
"json_schema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "clinical_note/v1",
"type": "object",
"required": ["chief_complaint", "present_illness", "treatment_plan"],
"properties": {
"current_date": {"type": "string"},
"next_appointment": {"type": "string"},
"chief_complaint": {"type": "string"},
"summary": {"type": "string"},
"present_illness": {"type": "string"},
"observations": {"type": "string"},
"treatment_plan": {"type": "string"},
"orders": {"type": "string"},
"vital_signs": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"value": {"type": "string"},
"unit": {"type": "string"},
"timestamp": {"type": "string", "format": "date-time"}
}
}
}
}
},
"target_language": "en"
}
response = requests.post(
"https://{your-endpoint}/v1/codify",
json=payload,
headers={
"Authorization": "Bearer YOUR_TOKEN",
"x-doctor": "dr_234",
"x-patient": "pt_567"
}
)
result = response.json()
print(result['data'])
Response
{
"data": {
"current_date": "2025-10-19T09:45:00Z",
"next_appointment": "",
"chief_complaint": "Sore throat and fever for 2 days",
"summary": "Probable pharyngotonsillitis; started on ibuprofen, rest and hydration; consider antigen test.",
"present_illness": "Pharyngeal pain, fever 38.5C, odynophagia. Tonsillar plaques, cervical lymphadenopathy.",
"observations": "Good general condition, no rash.",
"treatment_plan": "Ibuprofen 400mg every 8h for 3 days; rest; hydration.",
"orders": "Rapid streptococcal antigen test if available.",
"vital_signs": [
{ "name": "temperature", "value": "38.5", "unit": "C", "timestamp": "2025-10-19T09:40:00Z" }
]
},
"run_id": "run_def789"
}
Example 6: Oncology registry extraction
Use case
Automatically populate an oncology registry with data extracted from clinical notes.Complete request
import requests
payload = {
"input": "Patient diagnosed with left breast adenocarcinoma. Stage T2N1M0 (stage IIA). Hormone receptors positive (ER+, PR+), HER2 negative. Neoadjuvant chemotherapy protocol AC-T (adriamycin, cyclophosphamide followed by taxanes) initiated. Breast-conserving surgery planned after favorable response to chemotherapy.",
"json_schema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "oncology_registry/v1",
"type": "object",
"required": ["diagnosis", "location", "tnm_staging"],
"properties": {
"diagnosis": {"type": "string", "description": "Histological diagnosis"},
"icd10_code": {"type": "string", "source": "CIE-10-MC-ES-2026"},
"location": {"type": "string", "description": "Anatomical tumor location"},
"tnm_staging": {
"type": "object",
"properties": {
"t": {"type": "string"},
"n": {"type": "string"},
"m": {"type": "string"},
"stage": {"type": "string"}
}
},
"biomarkers": {
"type": "object",
"properties": {
"estrogen_receptors": {"type": "string"},
"progesterone_receptors": {"type": "string"},
"her2": {"type": "string"}
}
},
"planned_treatment": {"type": "string"},
"chemotherapy_protocol": {"type": "string"}
}
},
"target_language": "en"
}
response = requests.post(
"https://{your-endpoint}/v1/codify",
json=payload,
headers={
"Authorization": "Bearer YOUR_TOKEN",
"x-doctor": "dr_345",
"x-patient": "pt_678"
}
)
result = response.json()
print(result['data'])
Response
{
"data": {
"diagnosis": "Breast adenocarcinoma",
"icd10_code": "C50.9",
"location": "left breast",
"tnm_staging": { "t": "T2", "n": "N1", "m": "M0", "stage": "IIA" },
"biomarkers": {
"estrogen_receptors": "positive",
"progesterone_receptors": "positive",
"her2": "negative"
},
"planned_treatment": "Neoadjuvant chemotherapy followed by breast-conserving surgery",
"chemotherapy_protocol": "AC-T (adriamycin, cyclophosphamide followed by taxanes)"
},
"run_id": "run_onco_001"
}
Example 7: Medication extraction
Use case
Extract prescribed medications with pharmacy system codes.Complete request
import requests
payload = {
"input": "Prescribed enalapril 10mg every 12 hours orally, atorvastatin 20mg nightly orally, and metformin 850mg every 8 hours with meals. Continue with aspirin 100mg at breakfast.",
"json_schema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"medications": {
"type": "array",
"items": {
"type": "object",
"properties": {
"name": {"type": "string"},
"pharmacy_code": {"type": "string", "source": "BOTPLUS-2024"},
"dosage": {"type": "string"},
"frequency": {"type": "string"},
"route": {"type": "string", "enum": ["oral", "iv", "im", "sc", "topical", "inhaled"]},
"special_instructions": {"type": "string"}
}
}
}
}
},
"configure": "Extract all medications with exact pharmacy codes. Do not invent codes.",
"target_language": "en"
}
response = requests.post(
"https://{your-endpoint}/v1/codify",
json=payload,
headers={
"Authorization": "Bearer YOUR_TOKEN",
"x-doctor": "dr_456",
"x-patient": "pt_789"
}
)
result = response.json()
print(result['data'])
Response
{
"data": {
"medications": [
{ "name": "Enalapril", "pharmacy_code": "652302", "dosage": "10 mg", "frequency": "every 12 hours", "route": "oral", "special_instructions": "" },
{ "name": "Atorvastatin", "pharmacy_code": "663798", "dosage": "20 mg", "frequency": "nightly", "route": "oral", "special_instructions": "" },
{ "name": "Metformin", "pharmacy_code": "651077", "dosage": "850 mg", "frequency": "every 8 hours", "route": "oral", "special_instructions": "with meals" },
{ "name": "Acetylsalicylic acid", "pharmacy_code": "651449", "dosage": "100 mg", "frequency": "every 24 hours", "route": "oral", "special_instructions": "at breakfast" }
]
},
"run_id": "run_med_001"
}
Example 8: Batch processing multiple notes
Use case
Process multiple clinical notes in parallel for efficient bulk coding.Complete request
import requests
import concurrent.futures
API_URL = "https://{your-endpoint}/v1/codify"
API_TOKEN = "YOUR_TOKEN"
headers = {
"Authorization": f"Bearer {API_TOKEN}",
"Content-Type": "application/json"
}
def codify_note(note_data):
"""Process a single medical note"""
payload = {
"medical_note": note_data['text'],
"model": "balanced"
}
# Add optional tracking headers
request_headers = headers.copy()
if 'doctor_id' in note_data:
request_headers['x-doctor'] = note_data['doctor_id']
if 'patient_id' in note_data:
request_headers['x-patient'] = note_data['patient_id']
response = requests.post(API_URL, json=payload, headers=request_headers)
return {
'note_id': note_data['id'],
'result': response.json()
}
# Sample notes to process
notes = [
{
'id': 'note_001',
'text': 'Patient with Type 2 Diabetes, controlled with Metformin.',
'doctor_id': 'dr_123',
'patient_id': 'pt_456'
},
{
'id': 'note_002',
'text': 'Hypertension, essential, well controlled on Lisinopril 10mg daily.',
'doctor_id': 'dr_124',
'patient_id': 'pt_457'
},
{
'id': 'note_003',
'text': 'Acute bronchitis with productive cough. Started on azithromycin.',
'doctor_id': 'dr_125',
'patient_id': 'pt_458'
}
]
# Process in parallel (max 10 concurrent requests)
def process_batch(notes, max_workers=10):
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(codify_note, note) for note in notes]
results = []
for future in concurrent.futures.as_completed(futures):
try:
results.append(future.result())
except Exception as e:
print(f"Error processing note: {e}")
return results
# Execute batch processing
results = process_batch(notes)
# Display results
for result in results:
print(f"\nNote ID: {result['note_id']}")
print(f"Codes found: {len(result['result']['final_code_assessments'])}")
for assessment in result['result']['final_code_assessments']:
print(f" - {assessment['code']}: {assessment['description']} ({assessment['confidence_percent']}%)")
Output
Note ID: note_001
Codes found: 2
- E11.9: Type 2 diabetes mellitus without complications (94.5%)
- Z79.84: Long term (current) use of oral hypoglycemic drugs (97.2%)
Note ID: note_002
Codes found: 1
- I10: Essential (primary) hypertension (96.8%)
Note ID: note_003
Codes found: 1
- J20.9: Acute bronchitis, unspecified (93.4%)
Best practices from examples
1. Use tracking headers
Always includex-doctor and x-patient headers for better audit trails:
headers = {
"Authorization": "Bearer YOUR_TOKEN",
"x-doctor": "dr_123",
"x-patient": "pt_456"
}
2. Filter by confidence threshold
Review codes with high confidence first:high_confidence = [
a for a in result['final_code_assessments']
if a['confidence_percent'] >= 85
]
3. Review discarded codes
Understand the AI’s decision-making process:for assessment in result['discarded_code_assessments']:
print(f"Rejected: {assessment['code']} - {assessment['justification']}")
4. Store run_id for debugging
Always save therun_id for troubleshooting:
database.save_coding_result({
'patient_id': 'pt_456',
'codes': result['final_code_assessments'],
'run_id': result['run_id'],
'timestamp': datetime.now()
})
5. Handle errors gracefully
try:
response = requests.post(url, json=payload, headers=headers)
response.raise_for_status()
result = response.json()
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
# Rate limit - implement backoff
time.sleep(60)
retry()
elif e.response.status_code == 413:
# Payload too large - split the note
split_and_process()
else:
# Log and handle other errors
logger.error(f"API error: {e.response.json()}")
Next steps
Error Handling
Learn about error codes and retry strategies
Request Structure
Complete field reference
Authentication
API tokens and security
Quick Start
Get started in 5 minutes