Skip to main content

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 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:

RequirementData Requestor OrganizationsHealthcare 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:

  1. Navigate to the Home section in HealthEx
  2. Locate your project in the projects list
  3. Click on the project to view its details
  4. 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.

warning

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

FieldDescription
First NameThe patient's given name
Last NameThe patient's family name
Contact InformationAt least one valid contact method (email or phone number)
Language PreferencePatient's preferred language (en for English, es for Spanish)

Optional Fields

The following fields are optional but recommended for better patient management:

FieldDescription
Contact PreferenceHow 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 IDA unique patient identifier from your external system (e.g., PAT-2024-001, MRN-12345, participant ID)
Date of BirthPatient'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., 6501234567 or +16501234567)

Stage 3: Contact Preference Defaults

If no contact preference is specified, the system applies defaults based on format-valid contact methods:

Available Contact MethodsDefault
Both valid email + phoneemail
Only valid emailemail
Only valid phonephone

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
note

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:

ExampleBehavior
Maria GarciaOnly phone provided → defaults to phone
David ChenEmpty 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.

warning

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:

TypePurposePatient StateWorkflowUse Case
PRESCREENING_REQUESTRequest access to patient health records to determine study eligibilityPRESCREEN_CONSENT_PENDINGPatient will be asked to provide consent for prescreening before full enrollmentWhen you need to review patient records first to determine if they meet study criteria
ENROLLMENT_REQUESTRequest direct enrollment in the projectENROLLINGPatient will be contacted directly for study enrollmentWhen patient eligibility has already been determined and you're ready for direct enrollment
INFORMATION_SENTShare information about the project without requesting record accessINFORMATION_SENTPatient receives study information but no immediate action is requestedWhen providing educational materials or study awareness without immediate enrollment intent

Automatic Data Processing

When you provide an MRN, the system automatically:

  1. 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)
  2. 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
  3. Sets Contact Preference: Uses intelligent defaults based on available contact information:

    Available Contact MethodsDefault
    Email and phone (both valid)email
    Only email validemail
    Only phone validphone
  4. Handles Missing Contact Information: If the patient record lacks sufficient contact information, the addition will fail with a validation error

MRN Validation Rules

RuleDescription
FormatMRNs must contain only alphanumeric characters
ExistenceMRNs must exist in your organization's EHR system
AccessYour API credentials must have access to the patient record associated with the MRN
UniquenessDuplicate MRNs within the same API request will be rejected
Project ScopePatients 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"
}
]
}
MRNExplanation
MRN123456Placed in prescreening consent pending state, requiring consent before eligibility review
MRN789012Placed in enrolling state for direct study enrollment contact
MRN345678Placed in information sent state, having received study information without immediate action required
MRN999888Placed 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"
}
]
}
note

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

FieldDescription
totalProcessedTotal number of patient records included in your request
successCountNumber of patients successfully added to the project
errorCountNumber of patients that failed validation and were not added
duplicatesCountNumber of patients identified as duplicates and not added

Error Details

errors: Array containing details about validation failures

FieldDescription
patientIndexPosition of the failed patient in your original request array (0-based)
errorHuman-readable description of what went wrong

Duplicate Details

duplicates: Array containing details about duplicate patients found

FieldDescription
patientIndexPosition of the duplicate patient in your original request array (0-based)
existingPatientIdReference ID of the existing patient already in the system
duplicateFieldsList of fields that matched the existing patient (e.g., ["email", "phone"])

Success Details

successfulPatients: Array containing details about successfully added patients

FieldDescription
patientIndexPosition of the successful patient in your original request array (0-based)
emailEmail address of the patient (if provided)
phonePhone number of the patient (if provided)
mrnMedical Record Number of the patient (for healthcare organization additions)
externalIdExternal ID of the patient (if provided)
referenceIdReference 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:

GuaranteeDescription
Partial successSuccessful patients are added even if others fail
Individual validationEach patient is validated independently
Error isolationOne invalid patient doesn't prevent others from being processed
Atomic operationsDatabase operations are wrapped in transactions for consistency
Preference managementOnly 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:

ErrorMessage
Inactive studyPatients can only be added to active studies. This study is not currently active.
Missing required fieldsFirst name is required and cannot be empty
Invalid email formatInvalid email format "invalid-email-address"
Invalid phone numberInvalid phone number format "invalid-phone"
Missing contact informationAt least one of email or phone must be provided
Invalid contact preferenceContact preference is set to 'email' but no valid email address provided
Invalid language preferenceLanguage preference must be either 'en' (English) or 'es' (Spanish)

Healthcare Organization (MRN-Based)

Additional validation errors specific to MRN-based patient addition:

ErrorMessage
MRN not foundPatient not found with this MRN
Search failureFailed to search for patient
Validation failurePatient validation failed
Patient already in projectPatient 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_REQUEST when you need to review patient eligibility first
    • Use ENROLLMENT_REQUEST when patients are ready for direct enrollment (this is also the default if not specified)
    • Use INFORMATION_SENT when providing study information without immediate action
    • Omit patientNotificationType to use the default enrollment workflow
  • 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:

  1. Data Extraction: Extract patient data from your source system
  2. Data Validation: Perform local validation and formatting
  3. Batch Preparation: Group patients into appropriate batch sizes
  4. API Request: Submit batches to the HealthEx API
  5. Response Processing: Handle successful, failed, and duplicate patients
  6. Correlation: Use returned referenceId values for future reference
  7. Error Handling: Retry failed patients after addressing validation issues
  8. Audit Logging: Record all operations for compliance and troubleshooting

Troubleshooting (Applies to both)

General

Error MessageExplanation
"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 MessageExplanation
"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 MessageExplanation
"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:

  1. Check the API response for detailed error messages
  2. Verify your authentication credentials are valid and have appropriate permissions
  3. Ensure your project is active and not paused
  4. Review the patient data format against the requirements
  5. Contact HealthEx support with specific error messages and request details

See Also