Skip to main content

Class: MedplumClient

The MedplumClient class provides a client for the Medplum FHIR server.

The client can be used in the browser, in a Node.js application, or in a Medplum Bot.

The client provides helpful methods for common operations such as: 1) Authenticating 2) Creating resources 2) Reading resources 3) Updating resources 5) Deleting resources 6) Searching 7) Making GraphQL queries

Here is a quick example of how to use the client:

import { MedplumClient } from '@medplum/core';
const medplum = new MedplumClient();

Create a Patient:

const patient = await medplum.createResource({
resourceType: 'Patient',
name: [{
given: ['Alice'],
family: 'Smith'
}]
});

Read a Patient by ID:

const patient = await medplum.readResource('Patient', '123');
console.log(patient.name[0].given[0]);

Search for a Patient by name:

const bundle = await medplum.search('Patient', 'name=Alice');
console.log(bundle.total);

Hierarchy

  • EventTarget

    MedplumClient

Read

readResource

readResource<K>(resourceType, id, options?): ReadablePromise<ExtractResource<K>>

Reads a resource by resource type and ID.

Example:

const patient = await medplum.readResource('Patient', '123');
console.log(patient);

See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
idstringThe resource ID.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<ExtractResource<K>>

The resource if available; undefined otherwise.

Defined in

packages/core/src/client.ts:1316


readReference

readReference<T>(reference, options?): ReadablePromise<T>

Reads a resource by Reference.

This is a convenience method for readResource() that accepts a Reference object.

Example:

const serviceRequest = await medplum.readResource('ServiceRequest', '123');
const patient = await medplum.readReference(serviceRequest.subject);
console.log(patient);

See the FHIR "read" operation for full details: https://www.hl7.org/fhir/http.html#read

Type parameters

NameType
Textends Resource

Parameters

NameTypeDescription
referenceReference<T>The FHIR reference object.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<T>

The resource if available; undefined otherwise.

Defined in

packages/core/src/client.ts:1343


readHistory

readHistory<K>(resourceType, id, options?): ReadablePromise<Bundle<ExtractResource<K>>>

Reads resource history by resource type and ID.

The return value is a bundle of all versions of the resource.

Example:

const history = await medplum.readHistory('Patient', '123');
console.log(history);

See the FHIR "history" operation for full details: https://www.hl7.org/fhir/http.html#history

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
idstringThe resource ID.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<Bundle<ExtractResource<K>>>

Promise to the resource history.

Defined in

packages/core/src/client.ts:1456


readVersion

readVersion<K>(resourceType, id, vid, options?): ReadablePromise<ExtractResource<K>>

Reads a specific version of a resource by resource type, ID, and version ID.

Example:

const version = await medplum.readVersion('Patient', '123', '456');
console.log(version);

See the FHIR "vread" operation for full details: https://www.hl7.org/fhir/http.html#vread

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
idstringThe resource ID.
vidstringThe version ID.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<ExtractResource<K>>

The resource if available; undefined otherwise.

Defined in

packages/core/src/client.ts:1482


readPatientEverything

readPatientEverything(id, options?): ReadablePromise<Bundle<Resource>>

Executes the Patient "everything" operation for a patient.

Example:

const bundle = await medplum.readPatientEverything('123');
console.log(bundle);

See the FHIR "patient-everything" operation for full details: https://hl7.org/fhir/operation-patient-everything.html

Parameters

NameTypeDescription
idstringThe Patient Id
options?RequestInitOptional fetch options.

Returns

ReadablePromise<Bundle<Resource>>

A Bundle of all Resources related to the Patient

Defined in

packages/core/src/client.ts:1507


graphql

graphql(query, operationName?, variables?, options?): Promise<any>

Executes a GraphQL query.

Example:

const result = await medplum.graphql(`{
Patient(id: "123") {
resourceType
id
name {
given
family
}
}
}`);

Advanced queries such as named operations and variable substitution are supported:

const result = await medplum.graphql(
`query GetPatientById($patientId: ID!) {
Patient(id: $patientId) {
resourceType
id
name {
given
family
}
}
}`,
'GetPatientById',
{ patientId: '123' }
);

See the GraphQL documentation for more details: https://graphql.org/learn/

See the FHIR GraphQL documentation for FHIR specific details: https://www.hl7.org/fhir/graphql.html

Parameters

NameTypeDescription
querystringThe GraphQL query.
operationName?null | stringOptional GraphQL operation name.
variables?anyOptional GraphQL variables.
options?RequestInitOptional fetch options.

Returns

Promise<any>

The GraphQL result.

Defined in

packages/core/src/client.ts:2032


readResourceGraph

readResourceGraph<K>(resourceType, id, graphName, options?): ReadablePromise<Bundle<Resource>>

Executes the $graph operation on this resource to fetch a Bundle of resources linked to the target resource according to a graph definition

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
idstringThe resource ID.
graphNamestringname parameter of the GraphDefinition
options?RequestInitOptional fetch options.

Returns

ReadablePromise<Bundle<Resource>>

A Bundle

Defined in

packages/core/src/client.ts:2047


download

download(url, options?): Promise<Blob>

Downloads the URL as a blob.

Parameters

NameTypeDescription
urlstring | URLThe URL to request.
optionsRequestInitOptional fetch request init options.

Returns

Promise<Blob>

Promise to the response body as a blob.

Defined in

packages/core/src/client.ts:2228

Write

updateResource

updateResource<T>(resource, options?): Promise<T>

Updates a FHIR resource.

The return value is the updated resource, including the ID and meta.

Example:

const result = await medplum.updateResource({
resourceType: 'Patient',
id: '123',
name: [{
family: 'Smith',
given: ['John']
}]
});
console.log(result.meta.versionId);

See the FHIR "update" operation for full details: https://www.hl7.org/fhir/http.html#update

Type parameters

NameType
Textends Resource

Parameters

NameTypeDescription
resourceTThe FHIR resource to update.
options?RequestInitOptional fetch options.

Returns

Promise<T>

The result of the update operation.

Defined in

packages/core/src/client.ts:1770


patchResource

patchResource<K>(resourceType, id, operations, options?): Promise<ExtractResource<K>>

Updates a FHIR resource using JSONPatch operations.

The return value is the updated resource, including the ID and meta.

Example:

const result = await medplum.patchResource('Patient', '123', [
{op: 'replace', path: '/name/0/family', value: 'Smith'},
]);
console.log(result.meta.versionId);

See the FHIR "update" operation for full details: https://www.hl7.org/fhir/http.html#patch

See the JSONPatch specification for full details: https://tools.ietf.org/html/rfc6902

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
idstringThe resource ID.
operationsPatchOperation[]The JSONPatch operations.
options?RequestInitOptional fetch options.

Returns

Promise<ExtractResource<K>>

The result of the patch operations.

Defined in

packages/core/src/client.ts:1813

Create

createResource

createResource<T>(resource, options?): Promise<T>

Creates a new FHIR resource.

The return value is the newly created resource, including the ID and meta.

Example:

const result = await medplum.createResource({
resourceType: 'Patient',
name: [{
family: 'Smith',
given: ['John']
}]
});
console.log(result.id);

See the FHIR "create" operation for full details: https://www.hl7.org/fhir/http.html#create

Type parameters

NameType
Textends Resource

Parameters

NameTypeDescription
resourceTThe FHIR resource to create.
options?RequestInitOptional fetch options.

Returns

Promise<T>

The result of the create operation.

Defined in

packages/core/src/client.ts:1535


createResourceIfNoneExist

createResourceIfNoneExist<T>(resource, query, options?): Promise<T>

Conditionally create a new FHIR resource only if some equivalent resource does not already exist on the server.

The return value is the existing resource or the newly created resource, including the ID and meta.

Example:

const result = await medplum.createResourceIfNoneExist(
{
resourceType: 'Patient',
identifier: [{
system: 'http://example.com/mrn',
value: '123'
}]
name: [{
family: 'Smith',
given: ['John']
}]
},
'identifier=123'
);
console.log(result.id);

This method is syntactic sugar for:

return searchOne(resourceType, query) ?? createResource(resource);

The query parameter only contains the search parameters (what would be in the URL following the "?").

See the FHIR "conditional create" operation for full details: https://www.hl7.org/fhir/http.html#ccreate

Type parameters

NameType
Textends Resource

Parameters

NameTypeDescription
resourceTThe FHIR resource to create.
querystringThe search query for an equivalent resource (should not include resource type or "?").
options?RequestInitOptional fetch options.

Returns

Promise<T>

The result of the create operation.

Defined in

packages/core/src/client.ts:1583


createBinary

createBinary(data, filename, contentType, onProgress?): Promise<Binary>

Creates a FHIR Binary resource with the provided data content.

The return value is the newly created resource, including the ID and meta.

The data parameter can be a string or a File object.

A File object often comes from a <input type="file"> element.

Example:

const result = await medplum.createBinary(myFile, 'test.jpg', 'image/jpeg');
console.log(result.id);

See the FHIR "create" operation for full details: https://www.hl7.org/fhir/http.html#create

Parameters

NameTypeDescription
datastring | Uint8Array | File | BlobThe binary data to upload.
filenameundefined | stringOptional filename for the binary.
contentTypestringContent type for the binary.
onProgress?(e: ProgressEvent<EventTarget>) => voidOptional callback for progress events.

Returns

Promise<Binary>

The result of the create operation.

Defined in

packages/core/src/client.ts:1612


createComment

createComment(resource, text, options?): Promise<Communication>

Creates a FHIR Communication resource with the provided data content.

This is a convenience method to handle commmon cases where a Communication resource is created with a payload.

Parameters

NameTypeDescription
resourceResourceThe FHIR resource to comment on.
textstringThe text of the comment.
options?RequestInitOptional fetch options.

Returns

Promise<Communication>

The result of the create operation.

Defined in

packages/core/src/client.ts:1712

Delete

deleteResource

deleteResource(resourceType, id, options?): Promise<any>

Deletes a FHIR resource by resource type and ID.

Example:

await medplum.deleteResource('Patient', '123');

See the FHIR "delete" operation for full details: https://www.hl7.org/fhir/http.html#delete

Parameters

NameTypeDescription
resourceType"Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"The FHIR resource type.
idstringThe resource ID.
options?RequestInitOptional fetch options.

Returns

Promise<any>

The result of the delete operation.

Defined in

packages/core/src/client.ts:1839

Media

createPdf

createPdf(docDefinition, filename?, tableLayouts?, fonts?): Promise<Binary>

Creates a PDF as a FHIR Binary resource based on pdfmake document definition.

The return value is the newly created resource, including the ID and meta.

The docDefinition parameter is a pdfmake document definition.

Example:

const result = await medplum.createPdf({
content: ['Hello world']
});
console.log(result.id);

See the pdfmake document definition for full details: https://pdfmake.github.io/docs/0.1/document-definition-object/

Parameters

NameTypeDescription
docDefinitionTDocumentDefinitionsThe PDF document definition.
filename?stringOptional filename for the PDF binary resource.
tableLayouts?Record<string, CustomTableLayout>Optional pdfmake custom table layout.
fonts?TFontDictionaryOptional pdfmake custom font dictionary.

Returns

Promise<Binary>

The result of the create operation.

Defined in

packages/core/src/client.ts:1689


sendEmail

sendEmail(email, options?): Promise<OperationOutcome>

Sends an email using the Medplum Email API.

Builds the email using nodemailer MailComposer.

Examples:

Send a simple text email:

await medplum.sendEmail({
to: 'alice@example.com',
cc: 'bob@example.com',
subject: 'Hello',
text: 'Hello Alice',
});

Send an email with a Binary attachment:

await medplum.sendEmail({
to: 'alice@example.com',
subject: 'Email with attachment',
text: 'See the attached report',
attachments: [{
filename: 'report.pdf',
path: "Binary/" + binary.id
}]
});

See options here: https://nodemailer.com/extras/mailcomposer/

Parameters

NameTypeDescription
emailMailOptionsThe MailComposer options.
options?RequestInitOptional fetch options.

Returns

Promise<OperationOutcome>

Promise to the operation outcome.

Defined in

packages/core/src/client.ts:1981

Authentication

clear

clear(): void

Clears all auth state including local storage and session storage.

Returns

void

Defined in

packages/core/src/client.ts:623


clearActiveLogin

clearActiveLogin(): void

Clears the active login from local storage. Does not clear all local storage (such as other logins).

Returns

void

Defined in

packages/core/src/client.ts:633


startNewUser

startNewUser(newUserRequest, options?): Promise<LoginAuthenticationResponse>

Initiates a new user flow.

This method is part of the two different user registration flows: 1) New Practitioner and new Project 2) New Patient registration

Parameters

NameTypeDescription
newUserRequestNewUserRequestRegister request including email and password.
options?RequestInitOptional fetch options.

Returns

Promise<LoginAuthenticationResponse>

Promise to the authentication response.

Defined in

packages/core/src/client.ts:820


startLogin

startLogin(loginRequest, options?): Promise<LoginAuthenticationResponse>

Initiates a user login flow.

Parameters

NameTypeDescription
loginRequestEmailPasswordLoginRequestLogin request including email and password.
options?RequestInitOptional fetch options.

Returns

Promise<LoginAuthenticationResponse>

Promise to the authentication response.

Defined in

packages/core/src/client.ts:871


startGoogleLogin

startGoogleLogin(loginRequest, options?): Promise<LoginAuthenticationResponse>

Tries to sign in with Google authentication. The response parameter is the result of a Google authentication. See: https://developers.google.com/identity/gsi/web/guides/handle-credential-responses-js-functions

Parameters

NameTypeDescription
loginRequestGoogleLoginRequestLogin request including Google credential response.
options?RequestInitOptional fetch options.

Returns

Promise<LoginAuthenticationResponse>

Promise to the authentication response.

Defined in

packages/core/src/client.ts:896


ensureCodeChallenge

ensureCodeChallenge<T>(loginRequest): Promise<T>

Returns the PKCE code challenge and method. If the login request already includes a code challenge, it is returned. Otherwise, a new PKCE code challenge is generated.

Type parameters

NameType
Textends BaseLoginRequest

Parameters

NameTypeDescription
loginRequestTThe original login request.

Returns

Promise<T>

The PKCE code challenge and method.

Defined in

packages/core/src/client.ts:920


signOut

signOut(): Promise<void>

Signs out locally. Does not invalidate tokens with the server.

Returns

Promise<void>

Defined in

packages/core/src/client.ts:932


signInWithRedirect

signInWithRedirect(loginParams?): Promise<undefined | ProfileResource>

Tries to sign in the user. Returns true if the user is signed in. This may result in navigating away to the sign in page.

Parameters

NameTypeDescription
loginParams?Partial<BaseLoginRequest>Optional login parameters.

Returns

Promise<undefined | ProfileResource>

The user profile resource if available.

Defined in

packages/core/src/client.ts:945


signOutWithRedirect

signOutWithRedirect(): void

Tries to sign out the user. See: https://docs.aws.amazon.com/cognito/latest/developerguide/logout-endpoint.html

Returns

void

Defined in

packages/core/src/client.ts:961


signInWithExternalAuth

signInWithExternalAuth(authorizeUrl, clientId, redirectUri, baseLogin): Promise<void>

Initiates sign in with an external identity provider.

Parameters

NameTypeDescription
authorizeUrlstringThe external authorization URL.
clientIdstringThe external client ID.
redirectUristringThe external identity provider redirect URI.
baseLoginBaseLoginRequestThe Medplum login request.

Returns

Promise<void>

Defined in

packages/core/src/client.ts:973


exchangeExternalAccessToken

exchangeExternalAccessToken(token, clientId?): Promise<ProfileResource>

Exchange an external access token for a Medplum access token.

Parameters

NameTypeDescription
tokenstringThe access token that was generated by the external identity provider.
clientId?stringThe ID of the ClientApplication in your Medplum project that will be making the exchange request.

Returns

Promise<ProfileResource>

The user profile resource.

Defined in

packages/core/src/client.ts:990


getExternalAuthRedirectUri

getExternalAuthRedirectUri(authorizeUrl, clientId, redirectUri, loginRequest): string

Builds the external identity provider redirect URI.

Parameters

NameTypeDescription
authorizeUrlstringThe external authorization URL.
clientIdstringThe external client ID.
redirectUristringThe external identity provider redirect URI.
loginRequestBaseLoginRequestThe Medplum login request.

Returns

string

The external identity provider redirect URI.

Defined in

packages/core/src/client.ts:1013


getActiveLogin

getActiveLogin(): undefined | LoginState

Returns

undefined | LoginState

The Login State

Defined in

packages/core/src/client.ts:2060


setActiveLogin

setActiveLogin(login): Promise<void>

Sets the active login.

Parameters

NameTypeDescription
loginLoginStateThe new active login state.

Returns

Promise<void>

Defined in

packages/core/src/client.ts:2069


getAccessToken

getAccessToken(): undefined | string

Returns the current access token.

Returns

undefined | string

The current access token.

Defined in

packages/core/src/client.ts:2087


setAccessToken

setAccessToken(accessToken): void

Sets the current access token.

Parameters

NameTypeDescription
accessTokenstringThe new access token.

Returns

void

Defined in

packages/core/src/client.ts:2096


getLogins

getLogins(): LoginState[]

Returns the list of available logins.

Returns

LoginState[]

The list of available logins.

Defined in

packages/core/src/client.ts:2107


isLoading

isLoading(): boolean

Returns true if the client is waiting for authentication.

Returns

boolean

True if the client is waiting for authentication.

Defined in

packages/core/src/client.ts:2140


isSuperAdmin

isSuperAdmin(): boolean

Returns true if the current user is authenticated as a super admin.

Returns

boolean

True if the current user is authenticated as a super admin.

Defined in

packages/core/src/client.ts:2149


isProjectAdmin

isProjectAdmin(): boolean

Returns true if the current user is authenticated as a project admin.

Returns

boolean

True if the current user is authenticated as a project admin.

Defined in

packages/core/src/client.ts:2158


startPkce

startPkce(): Promise<{ codeChallengeMethod: string ; codeChallenge: string }>

Starts a new PKCE flow. These PKCE values are stateful, and must survive redirects and page refreshes.

Returns

Promise<{ codeChallengeMethod: string ; codeChallenge: string }>

The PKCE code challenge details.

Defined in

packages/core/src/client.ts:2630


processCode

processCode(code, loginParams?): Promise<ProfileResource>

Processes an OAuth authorization code. See: https://openid.net/specs/openid-connect-core-1_0.html#TokenRequest

Parameters

NameTypeDescription
codestringThe authorization code received by URL parameter.
loginParams?Partial<BaseLoginRequest>Optional login parameters.

Returns

Promise<ProfileResource>

The user profile resource.

Defined in

packages/core/src/client.ts:2671


startClientLogin

startClientLogin(clientId, clientSecret): Promise<ProfileResource>

Starts a new OAuth2 client credentials flow.

await medplum.startClientLogin(process.env.MEDPLUM_CLIENT_ID, process.env.MEDPLUM_CLIENT_SECRET)
// Example Search
await medplum.searchResources('Patient')

See: https://datatracker.ietf.org/doc/html/rfc6749#section-4.4

Parameters

NameTypeDescription
clientIdstringThe client ID.
clientSecretstringThe client secret.

Returns

Promise<ProfileResource>

Promise that resolves to the client profile.

Defined in

packages/core/src/client.ts:2731


setBasicAuth

setBasicAuth(clientId, clientSecret): void

Sets the client ID and secret for basic auth.

medplum.setBasicAuth(process.env.MEDPLUM_CLIENT_ID, process.env.MEDPLUM_CLIENT_SECRET)
// Example Search
await medplum.searchResources('Patient')

Parameters

NameTypeDescription
clientIdstringThe client ID.
clientSecretstringThe client secret.

Returns

void

Defined in

packages/core/src/client.ts:2754

fhirSearchUrl

fhirSearchUrl(resourceType, query): URL

Builds a FHIR search URL from a search query or structured query object.

Parameters

NameTypeDescription
resourceType"Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"The FHIR resource type.
queryQueryTypesThe FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.

Returns

URL

The well-formed FHIR URL.

Defined in

packages/core/src/client.ts:1047


search

search<K>(resourceType, query?, options?): ReadablePromise<Bundle<ExtractResource<K>>>

Sends a FHIR search request.

Example using a FHIR search string:

const bundle = await client.search('Patient', 'name=Alice');
console.log(bundle);

The return value is a FHIR bundle:

{
"resourceType": "Bundle",
"type": "searchset",
"entry": [
{
"resource": {
"resourceType": "Patient",
"name": [
{
"given": [
"George"
],
"family": "Washington"
}
],
}
}
]
}

To query the count of a search, use the summary feature like so:

const patients = medplum.search('Patient', '_summary=count');

See FHIR search for full details: https://www.hl7.org/fhir/search.html

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
query?QueryTypesOptional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<Bundle<ExtractResource<K>>>

Promise to the search result bundle.

Defined in

packages/core/src/client.ts:1102


searchOne

searchOne<K>(resourceType, query?, options?): ReadablePromise<undefined | ExtractResource<K>>

Sends a FHIR search request for a single resource.

This is a convenience method for search() that returns the first resource rather than a Bundle.

Example using a FHIR search string:

const patient = await client.searchOne('Patient', 'identifier=123');
console.log(patient);

The return value is the resource, if available; otherwise, undefined.

See FHIR search for full details: https://www.hl7.org/fhir/search.html

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
query?QueryTypesOptional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<undefined | ExtractResource<K>>

Promise to the first search result.

Defined in

packages/core/src/client.ts:1149


searchResources

searchResources<K>(resourceType, query?, options?): ReadablePromise<ExtractResource<K>[]>

Sends a FHIR search request for an array of resources.

This is a convenience method for search() that returns the resources as an array rather than a Bundle.

Example using a FHIR search string:

const patients = await client.searchResources('Patient', 'name=Alice');
console.log(patients);

The return value is an array of resources.

See FHIR search for full details: https://www.hl7.org/fhir/search.html

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
query?QueryTypesOptional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<ExtractResource<K>[]>

Promise to the array of search results.

Defined in

packages/core/src/client.ts:1190


searchResourcePages

searchResourcePages<K>(resourceType, query?, options?): AsyncGenerator<ExtractResource<K>[], any, unknown>

Creates an async generator over a series of FHIR search requests for paginated search results. Each iteration of the generator yields the array of resources on each page.

for await (const page of medplum.searchResourcePages('Patient', { _count: 10 })) {
for (const patient of page) {
console.log(`Processing Patient resource with ID: ${patient.id}`);
}
}

Yields

An async generator, where each result is an array of resources for each page.

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
query?QueryTypesOptional FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.
options?RequestInitOptional fetch options.

Returns

AsyncGenerator<ExtractResource<K>[], any, unknown>

Defined in

packages/core/src/client.ts:1230


searchValueSet

searchValueSet(system, filter, options?): ReadablePromise<ValueSet>

Searches a ValueSet resource using the "expand" operation. See: https://www.hl7.org/fhir/operation-valueset-expand.html

Parameters

NameTypeDescription
systemstringThe ValueSet system url.
filterstringThe search string.
options?RequestInitOptional fetch options.

Returns

ReadablePromise<ValueSet>

Promise to expanded ValueSet.

Defined in

packages/core/src/client.ts:1259

Caching

invalidateUrl

invalidateUrl(url): void

Invalidates any cached values or cached requests for the given URL.

Parameters

NameTypeDescription
urlstring | URLThe URL to invalidate.

Returns

void

Defined in

packages/core/src/client.ts:650


invalidateAll

invalidateAll(): void

Invalidates all cached values and flushes the cache.

Returns

void

Defined in

packages/core/src/client.ts:659


invalidateSearches

invalidateSearches<K>(resourceType): void

Invalidates all cached search results or cached requests for the given resourceType.

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe resource type to invalidate.

Returns

void

Defined in

packages/core/src/client.ts:668


getCached

getCached<K>(resourceType, id): undefined | ExtractResource<K>

Returns a cached resource if it is available.

Type parameters

NameType
Kextends "Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"

Parameters

NameTypeDescription
resourceTypeKThe FHIR resource type.
idstringThe FHIR resource ID.

Returns

undefined | ExtractResource<K>

The resource if it is available in the cache; undefined otherwise.

Defined in

packages/core/src/client.ts:1273


getCachedReference

getCachedReference<T>(reference): undefined | T

Returns a cached resource if it is available.

Type parameters

NameType
Textends Resource

Parameters

NameTypeDescription
referenceReference<T>The FHIR reference.

Returns

undefined | T

The resource if it is available in the cache; undefined otherwise.

Defined in

packages/core/src/client.ts:1284

Batch

executeBatch

executeBatch(bundle, options?): Promise<Bundle<Resource>>

Executes a batch or transaction of FHIR operations.

Example:

await medplum.executeBatch({
"resourceType": "Bundle",
"type": "transaction",
"entry": [
{
"fullUrl": "urn:uuid:61ebe359-bfdc-4613-8bf2-c5e300945f0a",
"resource": {
"resourceType": "Patient",
"name": [{ "use": "official", "given": ["Alice"], "family": "Smith" }],
"gender": "female",
"birthDate": "1974-12-25"
},
"request": {
"method": "POST",
"url": "Patient"
}
},
{
"fullUrl": "urn:uuid:88f151c0-a954-468a-88bd-5ae15c08e059",
"resource": {
"resourceType": "Patient",
"identifier": [{ "system": "http:/example.org/fhir/ids", "value": "234234" }],
"name": [{ "use": "official", "given": ["Bob"], "family": "Jones" }],
"gender": "male",
"birthDate": "1974-12-25"
},
"request": {
"method": "POST",
"url": "Patient",
"ifNoneExist": "identifier=http:/example.org/fhir/ids|234234"
}
}
]
});

See The FHIR "batch/transaction" section for full details: https://hl7.org/fhir/http.html#transaction

Parameters

NameTypeDescription
bundleBundle<Resource>The FHIR batch/transaction bundle.
options?RequestInitOptional fetch options.

Returns

Promise<Bundle<Resource>>

The FHIR batch/transaction response bundle.

Defined in

packages/core/src/client.ts:1939

HTTP

getBaseUrl

getBaseUrl(): string

Returns the current base URL for all API requests. By default, this is set to https://api.medplum.com/. This can be overridden by setting the baseUrl option when creating the client.

Returns

string

The current base URL for all API requests.

Defined in

packages/core/src/client.ts:604


getAuthorizeUrl

getAuthorizeUrl(): string

Returns the current authorize URL. By default, this is set to https://api.medplum.com/oauth2/authorize. This can be overridden by setting the authorizeUrl option when creating the client.

Returns

string

The current authorize URL.

Defined in

packages/core/src/client.ts:615


get

get<T>(url, options?): ReadablePromise<T>

Makes an HTTP GET request to the specified URL.

This is a lower level method for custom requests. For common operations, we recommend using higher level methods such as readResource(), search(), etc.

Type parameters

NameType
Tany

Parameters

NameTypeDescription
urlstring | URLThe target URL.
optionsRequestInitOptional fetch options.

Returns

ReadablePromise<T>

Promise to the response content.

Defined in

packages/core/src/client.ts:690


post

post(url, body, contentType?, options?): Promise<any>

Makes an HTTP POST request to the specified URL.

This is a lower level method for custom requests. For common operations, we recommend using higher level methods such as createResource().

Parameters

NameTypeDescription
urlstring | URLThe target URL.
bodyanyThe content body. Strings and File objects are passed directly. Other objects are converted to JSON.
contentType?stringThe content type to be included in the "Content-Type" header.
optionsRequestInitOptional fetch options.

Returns

Promise<any>

Promise to the response content.

Defined in

packages/core/src/client.ts:734


put

put(url, body, contentType?, options?): Promise<any>

Makes an HTTP PUT request to the specified URL.

This is a lower level method for custom requests. For common operations, we recommend using higher level methods such as updateResource().

Parameters

NameTypeDescription
urlstring | URLThe target URL.
bodyanyThe content body. Strings and File objects are passed directly. Other objects are converted to JSON.
contentType?stringThe content type to be included in the "Content-Type" header.
optionsRequestInitOptional fetch options.

Returns

Promise<any>

Promise to the response content.

Defined in

packages/core/src/client.ts:759


patch

patch(url, operations, options?): Promise<any>

Makes an HTTP PATCH request to the specified URL.

This is a lower level method for custom requests. For common operations, we recommend using higher level methods such as patchResource().

Parameters

NameTypeDescription
urlstring | URLThe target URL.
operationsPatchOperation[]Array of JSONPatch operations.
optionsRequestInitOptional fetch options.

Returns

Promise<any>

Promise to the response content.

Defined in

packages/core/src/client.ts:783


delete

delete(url, options?): Promise<any>

Makes an HTTP DELETE request to the specified URL.

This is a lower level method for custom requests. For common operations, we recommend using higher level methods such as deleteResource().

Parameters

NameTypeDescription
urlstring | URLThe target URL.
options?RequestInitOptional fetch options.

Returns

Promise<any>

Promise to the response content.

Defined in

packages/core/src/client.ts:803


fhirUrl

fhirUrl(...path): URL

Builds a FHIR URL from a collection of URL path components. For example, buildUrl('/Patient', '123') returns fhir/R4/Patient/123.

Parameters

NameTypeDescription
...pathstring[]The path component of the URL.

Returns

URL

The well-formed FHIR URL.

Defined in

packages/core/src/client.ts:1035


fhirSearchUrl

fhirSearchUrl(resourceType, query): URL

Builds a FHIR search URL from a search query or structured query object.

Parameters

NameTypeDescription
resourceType"Observation" | "Patient" | "Practitioner" | "RelatedPerson" | "AccessPolicy" | "Account" | "ActivityDefinition" | "AdverseEvent" | "AllergyIntolerance" | "Appointment" | "AppointmentResponse" | "AsyncJob" | "AuditEvent" | "Basic" | "Binary" | "BiologicallyDerivedProduct" | "BodyStructure" | "Bot" | "BulkDataExport" | "Bundle" | "CapabilityStatement" | "CarePlan" | "CareTeam" | "CatalogEntry" | "ChargeItem" | "ChargeItemDefinition" | "Claim" | "ClaimResponse" | "ClientApplication" | "ClinicalImpression" | "CodeSystem" | "Communication" | "CommunicationRequest" | "CompartmentDefinition" | "Composition" | "ConceptMap" | "Condition" | "Consent" | "Contract" | "Coverage" | "CoverageEligibilityRequest" | "CoverageEligibilityResponse" | "DetectedIssue" | "Device" | "DeviceDefinition" | "DeviceMetric" | "DeviceRequest" | "DeviceUseStatement" | "DiagnosticReport" | "DocumentManifest" | "DocumentReference" | "DomainConfiguration" | "EffectEvidenceSynthesis" | "Encounter" | "Endpoint" | "EnrollmentRequest" | "EnrollmentResponse" | "EpisodeOfCare" | "EventDefinition" | "Evidence" | "EvidenceVariable" | "ExampleScenario" | "ExplanationOfBenefit" | "FamilyMemberHistory" | "Flag" | "Goal" | "GraphDefinition" | "Group" | "GuidanceResponse" | "HealthcareService" | "ImagingStudy" | "Immunization" | "ImmunizationEvaluation" | "ImmunizationRecommendation" | "ImplementationGuide" | "InsurancePlan" | "Invoice" | "JsonWebKey" | "Library" | "Linkage" | "List" | "Location" | "Login" | "Measure" | "MeasureReport" | "Media" | "Medication" | "MedicationAdministration" | "MedicationDispense" | "MedicationKnowledge" | "MedicationRequest" | "MedicationStatement" | "MedicinalProduct" | "MedicinalProductAuthorization" | "MedicinalProductContraindication" | "MedicinalProductIndication" | "MedicinalProductIngredient" | "MedicinalProductInteraction" | "MedicinalProductManufactured" | "MedicinalProductPackaged" | "MedicinalProductPharmaceutical" | "MedicinalProductUndesirableEffect" | "MessageDefinition" | "MessageHeader" | "MolecularSequence" | "NamingSystem" | "NutritionOrder" | "ObservationDefinition" | "OperationDefinition" | "OperationOutcome" | "Organization" | "OrganizationAffiliation" | "Parameters" | "PasswordChangeRequest" | "PaymentNotice" | "PaymentReconciliation" | "Person" | "PlanDefinition" | "PractitionerRole" | "Procedure" | "Project" | "ProjectMembership" | "Provenance" | "Questionnaire" | "QuestionnaireResponse" | "RequestGroup" | "ResearchDefinition" | "ResearchElementDefinition" | "ResearchStudy" | "ResearchSubject" | "RiskAssessment" | "RiskEvidenceSynthesis" | "Schedule" | "SearchParameter" | "ServiceRequest" | "Slot" | "SmartAppLaunch" | "Specimen" | "SpecimenDefinition" | "StructureDefinition" | "StructureMap" | "Subscription" | "Substance" | "SubstanceNucleicAcid" | "SubstancePolymer" | "SubstanceProtein" | "SubstanceReferenceInformation" | "SubstanceSourceMaterial" | "SubstanceSpecification" | "SupplyDelivery" | "SupplyRequest" | "Task" | "TerminologyCapabilities" | "TestReport" | "TestScript" | "User" | "UserConfiguration" | "ValueSet" | "VerificationResult" | "VisionPrescription"The FHIR resource type.
queryQueryTypesThe FHIR search query or structured query object. Can be any valid input to the URLSearchParams() constructor.

Returns

URL

The well-formed FHIR URL.

Defined in

packages/core/src/client.ts:1047

Schema

getSchema

getSchema(): IndexedStructureDefinition

Returns a cached schema for a resource type. If the schema is not cached, returns undefined. It is assumed that a client will call requestSchema before using this method.

Deprecated

Use globalSchema instead.

Returns

IndexedStructureDefinition

The schema if immediately available, undefined otherwise.

Defined in

packages/core/src/client.ts:1366


requestSchema

requestSchema(resourceType): Promise<IndexedStructureDefinition>

Requests the schema for a resource type. If the schema is already cached, the promise is resolved immediately.

Parameters

NameTypeDescription
resourceTypestringThe FHIR resource type.

Returns

Promise<IndexedStructureDefinition>

Promise to a schema with the requested resource type.

Defined in

packages/core/src/client.ts:1377

User Profile

getProject

getProject(): undefined | Project

Returns the current project if available.

Returns

undefined | Project

The current project if available.

Defined in

packages/core/src/client.ts:2167


getProjectMembership

getProjectMembership(): undefined | ProjectMembership

Returns the current project membership if available.

Returns

undefined | ProjectMembership

The current project membership if available.

Defined in

packages/core/src/client.ts:2176


getProfile

getProfile(): undefined | ProfileResource

Returns the current user profile resource if available. This method does not wait for loading promises.

Returns

undefined | ProfileResource

The current user profile resource if available.

Defined in

packages/core/src/client.ts:2186


getProfileAsync

getProfileAsync(): Promise<undefined | ProfileResource>

Returns the current user profile resource if available. This method waits for loading promises.

Returns

Promise<undefined | ProfileResource>

The current user profile resource if available.

Defined in

packages/core/src/client.ts:2196


getUserConfiguration

getUserConfiguration(): undefined | UserConfiguration

Returns the current user configuration if available.

Returns

undefined | UserConfiguration

The current user configuration if available.

Defined in

packages/core/src/client.ts:2208


getAccessPolicy

getAccessPolicy(): undefined | AccessPolicy

Returns the current user access policy if available.

Returns

undefined | AccessPolicy

The current user access policy if available.

Defined in

packages/core/src/client.ts:2217

Other

constructor

new MedplumClient(options?)

Parameters

NameType
options?MedplumClientOptions

Overrides

EventTarget.constructor

Defined in

packages/core/src/client.ts:552


startNewProject

startNewProject(newProjectRequest, options?): Promise<LoginAuthenticationResponse>

Initiates a new project flow.

This requires a partial login from startNewUser or startNewGoogleUser.

Parameters

NameTypeDescription
newProjectRequestNewProjectRequestRegister request including email and password.
options?RequestInitOptional fetch options.

Returns

Promise<LoginAuthenticationResponse>

Promise to the authentication response.

Defined in

packages/core/src/client.ts:842


startNewPatient

startNewPatient(newPatientRequest, options?): Promise<LoginAuthenticationResponse>

Initiates a new patient flow.

This requires a partial login from startNewUser or startNewGoogleUser.

Parameters

NameTypeDescription
newPatientRequestNewPatientRequestRegister request including email and password.
options?RequestInitOptional fetch options.

Returns

Promise<LoginAuthenticationResponse>

Promise to the authentication response.

Defined in

packages/core/src/client.ts:857


uploadwithProgress

uploadwithProgress(url, data, contentType, onProgress): Promise<any>

Parameters

NameType
urlURL
datastring | Uint8Array | File | Blob
contentTypestring
onProgress(e: ProgressEvent<EventTarget>) => void

Returns

Promise<any>

Defined in

packages/core/src/client.ts:1630


validateResource

validateResource<T>(resource, options?): Promise<OperationOutcome>

Executes the validate operation with the provided resource.

Example:

const result = await medplum.validateResource({
resourceType: 'Patient',
name: [{ given: ['Alice'], family: 'Smith' }],
});

See the FHIR "$validate" operation for full details: https://www.hl7.org/fhir/resource-operation-validate.html

Type parameters

NameType
Textends Resource

Parameters

NameTypeDescription
resourceTThe FHIR resource.
options?RequestInitOptional fetch options.

Returns

Promise<OperationOutcome>

The validate operation outcome.

Defined in

packages/core/src/client.ts:1862


executeBot

executeBot(idOrIdentifier, body, contentType?, options?): Promise<any>

Executes a bot by ID or Identifier.

Parameters

NameTypeDescription
idOrIdentifierstring | IdentifierThe Bot ID or Identifier.
bodyanyThe content body. Strings and File objects are passed directly. Other objects are converted to JSON.
contentType?stringThe content type to be included in the "Content-Type" header.
options?RequestInitOptional fetch options.

Returns

Promise<any>

The Bot return value.

Defined in

packages/core/src/client.ts:1874


uploadMedia

uploadMedia(contents, contentType, filename, additionalFields?, options?): Promise<Media>

Upload media to the server and create a Media instance for the uploaded content.

Parameters

NameTypeDescription
contentsstring | Uint8Array | File | BlobThe contents of the media file, as a string, Uint8Array, File, or Blob.
contentTypestringThe media type of the content.
filenameundefined | stringThe name of the file to be uploaded, or undefined if not applicable.
additionalFields?Partial<Media>Additional fields for Media.
options?RequestInitOptional fetch options.

Returns

Promise<Media>

Promise that resolves to the created Media

Defined in

packages/core/src/client.ts:2246


bulkExport

bulkExport(exportLevel?, resourceTypes?, since?, options?): Promise<Partial<BulkDataExport>>

Performs Bulk Data Export operation request flow. See The FHIR "Bulk Data Export" for full details: https://build.fhir.org/ig/HL7/bulk-data/export.html#bulk-data-export

Parameters

NameTypeDefault valueDescription
exportLevelstring''Optional export level. Defaults to system level export. 'Group/:id' - Group of Patients, 'Patient' - All Patients.
resourceTypes?stringundefinedA string of comma-delimited FHIR resource types.
since?stringundefinedResources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).
options?RequestInitundefinedOptional fetch options.

Returns

Promise<Partial<BulkDataExport>>

Bulk Data Response containing links to Bulk Data files. See "Response - Complete Status" for full details: https://build.fhir.org/ig/HL7/bulk-data/export.html#response---complete-status

Defined in

packages/core/src/client.ts:2276


startAsyncRequest

startAsyncRequest<T>(url, options?): Promise<T>

Starts an async request following the FHIR "Asynchronous Request Pattern". See: https://hl7.org/fhir/r4/async.html

Type parameters

Name
T

Parameters

NameTypeDescription
urlstringThe URL to request.
optionsRequestInitOptional fetch options.

Returns

Promise<T>

The response body.

Defined in

packages/core/src/client.ts:2303


invite

invite(projectId, body): Promise<OperationOutcome | ProjectMembership>

Invite a user to a project.

Parameters

NameTypeDescription
projectIdstringThe project ID.
bodyInviteBodyThe InviteBody.

Returns

Promise<OperationOutcome | ProjectMembership>

Promise that returns a project membership or an operation outcome.

Defined in

packages/core/src/client.ts:2766


addEventListener

addEventListener(type, callback): void

Parameters

NameType
typestring
callbackEventListener

Returns

void

Inherited from

EventTarget.addEventListener

Defined in

packages/core/src/eventtarget.ts:19


removeEventListeneer

removeEventListeneer(type, callback): void

Parameters

NameType
typestring
callbackEventListener

Returns

void

Inherited from

EventTarget.removeEventListeneer

Defined in

packages/core/src/eventtarget.ts:26


dispatchEvent

dispatchEvent(event): boolean

Parameters

NameType
eventEvent

Returns

boolean

Inherited from

EventTarget.dispatchEvent

Defined in

packages/core/src/eventtarget.ts:39