Add Patients by API
The HealthEx API lets both data requestor organizations and healthcare organizations add patients to their projects programmatically. Use it to bulk-import patient cohorts from external systems, EHRs, or research databases as part of your existing workflows.
Organization Types
The API supports two organization types, each with different capabilities. Select yours to jump to its steps.
- Data Requestor Organizations supply complete patient data directly.
- Healthcare Organizations add patients by Medical Record Number (MRN), with patient data retrieved automatically.
Data requestors can only use the patients array; healthcare organizations can only use the mrns array. Using the wrong one returns an authorization error.
Sections marked (Applies to both) are shared by both paths.
Prerequisites (Applies to both)
Before you can add patients to a project, you'll need:
| Requirement | Data Requestor Organizations | Healthcare Organizations |
|---|---|---|
| A HealthEx account | ✓ | ✓ |
| An active project (patients can only be added to active projects) | ✓ | ✓ |
| Valid API credentials (see Authentication) | ✓ | ✓ |
| Access to patient data through your EHR system | ✗ | ✓ |
| Patients exist in your EHR with valid MRNs | ✗ | ✓ |
All requests authenticate with a JWT token passed in the Authorization header. See the Authentication guide for setup.
Identifying Your Project (Applies to both)
Both paths need the project's unique identifier:
- Navigate to the Home section in HealthEx
- Locate your project in the projects list
- Click on the project to view its details
- The project ID can be found in the URL:
https://app.healthex.io/#/projects/{project-id}/patient-management
Data Requestor Path
Provide complete patient information — names, contact details, and preferences — directly in your API request.
Data requestors can only use the patients array, not the mrns array. Using MRNs returns an authorization error.
Patient Data Requirements
Each patient record must include the following required information:
Required Fields
| Field | Description |
|---|---|
| First Name | The patient's given name |
| Last Name | The patient's family name |
| Contact Information | At least one valid contact method (email or phone number) |
| Language Preference | Patient's preferred language (en for English, es for Spanish) |
Optional Fields
The following fields are optional but recommended for better patient management:
| Field | Description |
|---|---|
| Contact Preference | How the patient prefers to be contacted (email or phone). If not provided, the system defaults to email when both contact methods are available, or to the single available method. |
| External ID | A unique patient identifier from your external system (e.g., PAT-2024-001, MRN-12345, participant ID) |
| Date of Birth | Patient's birth date in MM/DD/YYYY format |
Contact Information & Validation
The system employs a multi-stage validation process. These rules also apply to contact data retrieved automatically via MRN (see the Healthcare Organization Path).
Stage 1: Presence Validation
- At least one contact method (email or phone) must be provided
- Empty or whitespace-only email and phone fields are ignored (treated as not provided)
Stage 2: Format Validation
- Email addresses: Must follow standard email format (e.g.,
patient@example.com) - Phone numbers: Must be valid US phone numbers (e.g.,
6501234567or+16501234567)
Stage 3: Contact Preference Defaults
If no contact preference is specified, the system applies defaults based on format-valid contact methods:
| Available Contact Methods | Default |
|---|---|
| Both valid email + phone | email |
| Only valid email | email |
| Only valid phone | phone |
Stage 4: Business Logic Validation
- Contact preference must match an available format-valid contact method
- Setting
contactPreference: "email"requires a valid email address - Setting
contactPreference: "phone"requires a valid phone number
Contact preference defaults are only applied to format-valid contact methods. Providing an invalid email and setting contactPreference: "email" will result in validation failure.
Example Request
{
"patients": [
{
"firstName": "Sarah",
"lastName": "Johnson",
"externalId": "PAT-2024-001",
"dateOfBirth": "03/15/1985",
"email": "sarah.johnson@email.com",
"phone": "5551234567",
"contactPreference": "email",
"languagePreference": "en"
},
{
"firstName": "Carlos",
"lastName": "Rodriguez",
"email": "carlos.rodriguez@email.com",
"phone": "5559876543",
"contactPreference": "phone",
"languagePreference": "es"
},
{
"firstName": "Maria",
"lastName": "Garcia",
"phone": "5551112222",
"languagePreference": "es"
},
{
"firstName": "David",
"lastName": "Chen",
"email": "david.chen@email.com",
"phone": "5554445555",
"languagePreference": "en"
}
]
}
Note: Examples 3 and 4 show automatic contact preference defaulting:
| Example | Behavior |
|---|---|
| Maria Garcia | Only phone provided → defaults to phone |
| David Chen | Empty contactPreference with both contacts → defaults to email |
Making the Call
POST https://api.healthex.io/v1/projects/{projectId}/patients
Content-Type: application/json
Authorization: Bearer <your JWT token>
{
"patients": [
{
"firstName": "Sarah",
"lastName": "Johnson",
"externalId": "PAT-2024-001",
"dateOfBirth": "03/15/1985",
"email": "sarah.johnson@email.com",
"phone": "5551234567",
"contactPreference": "email",
"languagePreference": "en"
}
]
}
Replace {projectId} with your actual project ID. See Understanding the Response for how to read the result.
Healthcare Organization (MRN) Path
Provide only Medical Record Numbers (MRNs) along with a notification type. The system automatically fetches patient details from your EHR system, validates and formats contact information, sets patient states based on your notification type, and handles language preferences from patient records.
Healthcare organizations can only use the mrns array, not the patients array. Using direct patient data returns an authorization error.
MRN Requirements
Each MRN record must include:
Required Fields
- MRN: A valid Medical Record Number that exists in your EHR system
Optional Fields
- Patient Notification Type: Specifies how the patient should be contacted and what initial state they should be placed in. If not provided, defaults to
ENROLLMENT_REQUEST.
Patient Notification Types
The system supports three notification types that determine the patient's initial state and contact approach:
| Type | Purpose | Patient State | Workflow | Use Case |
|---|---|---|---|---|
PRESCREENING_REQUEST | Request access to patient health records to determine study eligibility | PRESCREEN_CONSENT_PENDING | Patient will be asked to provide consent for prescreening before full enrollment | When you need to review patient records first to determine if they meet study criteria |
ENROLLMENT_REQUEST | Request direct enrollment in the project | ENROLLING | Patient will be contacted directly for study enrollment | When patient eligibility has already been determined and you're ready for direct enrollment |
INFORMATION_SENT | Share information about the project without requesting record access | INFORMATION_SENT | Patient receives study information but no immediate action is requested | When providing educational materials or study awareness without immediate enrollment intent |
Automatic Data Processing
When you provide an MRN, the system automatically:
-
Retrieves Patient Data: Fetches patient details from your EHR system including:
- First and last name
- Email address (if available)
- Phone number (if available)
- Date of birth
- Language preference (English/Spanish based on patient records)
-
Validates Contact Information: Applies the same rules described in Contact Information & Validation:
- Ensures at least one valid contact method (email or phone) is available
- Validates email format and phone number format
- Automatically sets contact preference based on available valid contact methods
-
Sets Contact Preference: Uses intelligent defaults based on available contact information:
Available Contact Methods Default Email and phone (both valid) emailOnly email valid emailOnly phone valid phone -
Handles Missing Contact Information: If the patient record lacks sufficient contact information, the addition will fail with a validation error
MRN Validation Rules
| Rule | Description |
|---|---|
| Format | MRNs must contain only alphanumeric characters |
| Existence | MRNs must exist in your organization's EHR system |
| Access | Your API credentials must have access to the patient record associated with the MRN |
| Uniqueness | Duplicate MRNs within the same API request will be rejected |
| Project Scope | Patients cannot be added multiple times to the same project |
Example Request
{
"mrns": [
{
"mrn": "MRN123456",
"patientNotificationType": "PRESCREENING_REQUEST"
},
{
"mrn": "MRN789012",
"patientNotificationType": "ENROLLMENT_REQUEST"
},
{
"mrn": "MRN345678",
"patientNotificationType": "INFORMATION_SENT"
},
{
"mrn": "MRN999888"
}
]
}
| MRN | Explanation |
|---|---|
MRN123456 | Placed in prescreening consent pending state, requiring consent before eligibility review |
MRN789012 | Placed in enrolling state for direct study enrollment contact |
MRN345678 | Placed in information sent state, having received study information without immediate action required |
MRN999888 | Placed in the default enrolling state (same as ENROLLMENT_REQUEST) since no notification type was specified |
Automatic Data Retrieval: For each MRN, the system automatically fetches patient details from your EHR system including name, contact information, date of birth, and language preference. Contact preference is determined based on available and valid contact methods in the patient record.
Making the Call
POST https://api.healthex.io/v1/projects/{projectId}/patients
Content-Type: application/json
Authorization: Bearer <your JWT token>
{
"mrns": [
{
"mrn": "MRN123456",
"patientNotificationType": "PRESCREENING_REQUEST"
},
{
"mrn": "MRN789012",
"patientNotificationType": "ENROLLMENT_REQUEST"
},
{
"mrn": "MRN345678",
"patientNotificationType": "INFORMATION_SENT"
},
{
"mrn": "MRN999888"
}
]
}
The patientNotificationType field is optional. If not provided, it defaults to ENROLLMENT_REQUEST, placing the patient in an enrolling state for direct study enrollment contact.
Replace {projectId} with your actual project ID. See Understanding the Response for how to read the result.
Understanding the Response (Applies to both)
The API processes all patients in your request and returns a response showing detailed results:
{
"totalProcessed": 4,
"successCount": 2,
"errorCount": 1,
"duplicatesCount": 1,
"errors": [
{
"patientIndex": 2,
"error": "Patient could not be added: Contact preference is set to 'email' but no valid email address provided"
}
],
"duplicates": [
{
"patientIndex": 3,
"existingPatientId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"duplicateFields": ["email"]
}
],
"successfulPatients": [
{
"patientIndex": 0,
"email": "sarah.johnson@email.com",
"phone": "5551234567",
"mrn": "MRN123456",
"referenceId": "hx_abc123def456"
},
{
"patientIndex": 1,
"email": "carlos.rodriguez@email.com",
"phone": "5559876543",
"mrn": "MRN789012",
"referenceId": "hx_def789ghi012"
}
]
}
Response Fields Explained
Summary Counts
| Field | Description |
|---|---|
totalProcessed | Total number of patient records included in your request |
successCount | Number of patients successfully added to the project |
errorCount | Number of patients that failed validation and were not added |
duplicatesCount | Number of patients identified as duplicates and not added |
Error Details
errors: Array containing details about validation failures
| Field | Description |
|---|---|
patientIndex | Position of the failed patient in your original request array (0-based) |
error | Human-readable description of what went wrong |
Duplicate Details
duplicates: Array containing details about duplicate patients found
| Field | Description |
|---|---|
patientIndex | Position of the duplicate patient in your original request array (0-based) |
existingPatientId | Reference ID of the existing patient already in the system |
duplicateFields | List of fields that matched the existing patient (e.g., ["email", "phone"]) |
Success Details
successfulPatients: Array containing details about successfully added patients
| Field | Description |
|---|---|
patientIndex | Position of the successful patient in your original request array (0-based) |
email | Email address of the patient (if provided) |
phone | Phone number of the patient (if provided) |
mrn | Medical Record Number of the patient (for healthcare organization additions) |
externalId | External ID of the patient (if provided) |
referenceId | Reference ID of the patient in HealthEx |
Example Responses by Org Type
Data Requestor
For data requestors using direct patient data:
{
"successfulPatients": [
{
"patientIndex": 0,
"email": "datarequestor.patient@email.com",
"phone": "+15551234567",
"externalId": "EXT-PAT-001",
"referenceId": "hx_abc123def456"
}
]
}
Healthcare Organization (MRN)
For healthcare organizations using MRN-based additions, the mrn field contains the Medical Record Number:
{
"successfulPatients": [
{
"patientIndex": 0,
"email": "patient@hospital.com",
"phone": "+15559876543",
"mrn": "MRN123456",
"referenceId": "hx_def789ghi012"
}
]
}
Advanced Processing Features (Applies to both)
Duplicate Detection
The system uses a two-tier duplicate detection strategy.
Database-Level Duplicates
Checks each patient against those already in the project.
- Matches on email addresses and phone numbers, including raw and normalized E.164 formats
- Returns the reference ID of the existing patient for correlation
Batch-Level Duplicates
Prevents duplicates within the same API request.
- The first occurrence of duplicate data is processed; subsequent ones are rejected
- Marked with
existingPatientId: "local"to indicate within-batch duplication
Automatic Patient Preferences
For successfully added patients, the system automatically:
- Creates patient preference records based on contact and language preferences
- Respects existing preferences if the patient already has them in the system
- Sets appropriate default values for first-time login and opt-out status
Batch Processing Behavior
The API processes patients with the following guarantees:
| Guarantee | Description |
|---|---|
| Partial success | Successful patients are added even if others fail |
| Individual validation | Each patient is validated independently |
| Error isolation | One invalid patient doesn't prevent others from being processed |
| Atomic operations | Database operations are wrapped in transactions for consistency |
| Preference management | Only creates new preferences if none exist |
Handling Common Validation Errors (Applies to both)
Data Requestor
The system will reject patients that don't meet validation requirements:
| Error | Message |
|---|---|
| Inactive study | Patients can only be added to active studies. This study is not currently active. |
| Missing required fields | First name is required and cannot be empty |
| Invalid email format | Invalid email format "invalid-email-address" |
| Invalid phone number | Invalid phone number format "invalid-phone" |
| Missing contact information | At least one of email or phone must be provided |
| Invalid contact preference | Contact preference is set to 'email' but no valid email address provided |
| Invalid language preference | Language preference must be either 'en' (English) or 'es' (Spanish) |
Healthcare Organization (MRN-Based)
Additional validation errors specific to MRN-based patient addition:
| Error | Message |
|---|---|
| MRN not found | Patient not found with this MRN |
| Search failure | Failed to search for patient |
| Validation failure | Patient validation failed |
| Patient already in project | Patient is already part of this project |
Plus all the same field validation errors as data requestors when patient data is retrieved from the EHR system.
Best Practices (Applies to both)
For Data Requestors
- Validate data locally: Use valid US phone formats and ensure contact preferences match available methods
- Use external IDs to maintain correlation with your internal systems
- Batch requests with no more than 1000 patients per request for optimal performance
- Handle partial failures: Always check responses for errors/duplicates and retry failed records
For Healthcare Organizations (MRN-Based)
- Validate MRN format: Ensure valid MRNs are sent
- Choose appropriate notification types: Optionally select the notification type that matches your intended patient workflow:
- Use
PRESCREENING_REQUESTwhen you need to review patient eligibility first - Use
ENROLLMENT_REQUESTwhen patients are ready for direct enrollment (this is also the default if not specified) - Use
INFORMATION_SENTwhen providing study information without immediate action - Omit
patientNotificationTypeto use the default enrollment workflow
- Use
- Ensure EHR data quality: Verify patient records have valid contact information (email or phone) before adding
- Monitor EHR connectivity: Implement retry logic for EHR system connectivity issues
- Batch MRN requests: Group MRNs into batches of no more than 500 per request for optimal performance
- Handle automatic data mapping: Trust the system's automatic contact preference and language preference detection based on EHR data
Integration Workflow Example (Applies to both)
Here's a typical integration workflow:
- Data Extraction: Extract patient data from your source system
- Data Validation: Perform local validation and formatting
- Batch Preparation: Group patients into appropriate batch sizes
- API Request: Submit batches to the HealthEx API
- Response Processing: Handle successful, failed, and duplicate patients
- Correlation: Use returned
referenceIdvalues for future reference - Error Handling: Retry failed patients after addressing validation issues
- Audit Logging: Record all operations for compliance and troubleshooting
Troubleshooting (Applies to both)
General
| Error Message | Explanation |
|---|---|
| "Not authorized for organization" | Ensure your API key has access to the organization that owns the project. |
| "Paused projects cannot add patients" | Check if the project is currently paused in the HealthEx web application. |
| "Patients can only be added to active studies" | Ensure your project status is set to Active in HealthEx. Patients cannot be added to Draft, Completed, or Withdrawn studies. |
| "Duplicate information detected" | This indicates a unique constraint violation in the database, usually due to race conditions or system-level duplicates. |
| "Contact information matches multiple existing patients" | The provided email or phone number matches multiple patients in the system, creating ambiguity in patient identification. |
Data Requestor Specific
| Error Message | Explanation |
|---|---|
| "Data requestors cannot add patients using MRNs" | Data requestors must use the patients array and cannot use the mrns array. Verify you are sending patient data in the patients array. |
| "Data requestors must provide patient data using the 'patients' array" | Ensure you are including the patients array with at least one patient record in your request. |
| "Invalid phone number format" | Ensure phone numbers are valid US phone numbers (e.g., 6501234567 or +16501234567). The validator accepts both 10-digit and +1 prefixed formats. |
| "Contact preference is set to 'email' but no valid email address provided" | The contact preference must match a provided and format-valid contact method. Check that the email address is properly formatted. |
Healthcare Organization (MRN-Based) Specific
| Error Message | Explanation |
|---|---|
| "Healthcare organizations cannot add patients using direct patient data" | Healthcare organizations must use the mrns array and cannot use the patients array. Verify you are sending MRN data in the mrns array. |
| "Healthcare organizations must provide patient data using the 'mrns' array" | Ensure you are including the mrns array with at least one MRN record in your request. |
| "MRN must contain only letters and numbers" | Ensure MRNs only contain alphanumeric characters. Remove any dashes, spaces, or special characters. |
| "Patient not found with this MRN" | The MRN does not exist in your EHR system or your organization does not have access to this patient record. |
| "Invalid patientNotificationType" | If provided, the patientNotificationType must be one of the valid values: PRESCREENING_REQUEST, ENROLLMENT_REQUEST, or INFORMATION_SENT. |
| "Failed to retrieve patient data from EHR system" | There was an error connecting to or retrieving data from your EHR system. Check your system connectivity and try again. |
| "Patient record lacks required contact information" | The patient record in your EHR system does not have a valid email address or phone number. Update the patient record in your EHR system before adding to HealthEx. |
| "Patient is already part of this project" | The patient associated with this MRN has already been added to this project. Use the patient management interface to view existing patients. |
Getting Help
If you encounter issues not covered in this documentation:
- Check the API response for detailed error messages
- Verify your authentication credentials are valid and have appropriate permissions
- Ensure your project is active and not paused
- Review the patient data format against the requirements
- Contact HealthEx support with specific error messages and request details
See Also
- Authentication: Learn how to set up API credentials and manage tokens
- Basic Consent Checking: Understand how patient consent works in HealthEx