Skip to main content
This page contains complete API usage examples for different clinical scenarios with the Codify ICD-10 medical coding API.

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"
}
Interpretation:
  • 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"
}
Interpretation:
  • 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, containing final_code_assessments, discarded_code_assessments, and run_id.

Example 4: 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 include x-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 the run_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