Skip to main content

core.medplumclient

Home > @medplum/core > MedplumClient

MedplumClient class

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 3. Reading resources 4. Updating resources 5. Deleting resources 6. Searching 7. Making GraphQL queries

The client can also be used to integrate with other FHIR servers. For an example, see the Epic Connection Demo Bot [here](https://github.com/medplum/medplum/tree/main/examples/medplum-demo-bots/src/epic).

Signature:

export declare class MedplumClient extends TypedEventTarget<MedplumClientEventMap> 

Extends: TypedEventTarget<MedplumClientEventMap>

Example 1

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

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

Example 2

Create a Patient:

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

Example 3

Read a Patient by ID:

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

Example 4

Search for a Patient by name:

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

Constructors

Constructor

Modifiers

Description

(constructor)(options)

Constructs a new instance of the MedplumClient class

Properties

Property

Modifiers

Type

Description

isInitialized

readonly

boolean

keyValue

readonly

MedplumKeyValueClient

Returns the key value client.

Methods

Method

Modifiers

Description

bulkExport(exportLevel, resourceTypes, since, options)

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

clear()

Clears all auth state including local storage and session storage.

clearActiveLogin()

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

createAttachment(createBinaryOptions, requestOptions)

Creates a FHIR Attachment with the provided data content.

This is a convenience method for creating a Binary resource and then creating an Attachment element.

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

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

createAttachment(data, filename, contentType, onProgress, options)

createBinary(createBinaryOptions, requestOptions)

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.

createBinary(data, filename, contentType, onProgress, options)

createComment(resource, text, options)

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.

createMedia(createMediaOptions, requestOptions)

Creates a FHIR Media resource with the provided data content.

createPdf(createPdfOptions, requestOptions)

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.

createPdf(docDefinition, filename, tableLayouts, fonts)

createResource(resource, options)

Creates a new FHIR resource.

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

createResourceIfNoneExist(resource, query, options)

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.

delete(url, options)

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().

deleteResource(resourceType, id, options)

Deletes a FHIR resource by resource type and ID.

download(url, options)

Downloads the URL as a blob. Can accept binary URLs in the form of Binary/{id} as well.

ensureCodeChallenge(loginRequest)

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.

exchangeExternalAccessToken(token, clientId)

Exchange an external access token for a Medplum access token.

executeBatch(bundle, options)

Executes a batch or transaction of FHIR operations.

executeBot(idOrIdentifier, body, contentType, options)

Executes a bot by ID or Identifier.

fhircastConnect(subRequest)

Connects to a FHIRcast session.

fhircastGetContext(topic)

Gets the current context of the given FHIRcast topic.

fhircastPublish(topic, event, context, versionId)

Publishes a new context to a given topic for a specified event type.

fhircastPublish(topic, event, context, versionId)

fhircastSubscribe(topic, events)

Subscribes to a specified topic, listening for a list of specified events.

Once you have the SubscriptionRequest returned from this method, you can call fhircastConnect(subscriptionRequest) to connect to the subscription stream.

fhircastUnsubscribe(subRequest)

Unsubscribes from the specified topic.

fhirSearchUrl(resourceType, query)

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

fhirUrl(path)

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

get(url, options)

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.

getAccessPolicy()

Returns the current user access policy if available.

getAccessToken()

Returns the current access token.

getActiveLogin()

getAuthorizeUrl()

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.

getBaseUrl()

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.

getCached(resourceType, id)

Returns a cached resource if it is available.

getCachedReference(reference)

Returns a cached resource if it is available.

getExternalAuthRedirectUri(authorizeUrl, clientId, redirectUri, loginRequest, pkceEnabled)

Builds the external identity provider redirect URI.

getInitPromise()

Gets a Promise that resolves when async initialization is complete. This is particularly useful for waiting for an async ClientStorage and/or authentication to finish.

getLogins()

Returns the list of available logins.

getLogoutUrl()

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

getMasterSubscriptionEmitter()

Get the master SubscriptionEmitter for the SubscriptionManager.

The master SubscriptionEmitter gets messages for all subscribed criteria as well as WebSocket errors, connect and disconnect events, and the close event.

It can also be used to listen for heartbeat messages.

------

getProfile()

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

getProfileAsync()

Returns the current user profile resource, retrieving form the server if necessary. This method waits for loading promises.

getProject()

Returns the current project if available.

getProjectMembership()

Returns the current project membership if available.

getSubscriptionManager()

Gets the SubscriptionManager for WebSocket subscriptions.

getTokenUrl()

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

getUserConfiguration()

Returns the current user configuration if available.

graphql(query, operationName, variables, options)

Executes a GraphQL query.

invalidateAll()

Invalidates all cached values and flushes the cache.

invalidateSearches(resourceType)

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

invalidateUrl(url)

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

invite(projectId, body)

Invite a user to a project.

isLoading()

Returns true if the client is waiting for authentication.

isProjectAdmin()

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

isSuperAdmin()

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

patch(url, operations, options)

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().

patchResource(resourceType, id, operations, options)

Updates a FHIR resource using JSONPatch operations.

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

post(url, body, contentType, options)

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().

processCode(code, loginParams)

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

pushToAgent(agent, destination, body, contentType, waitForResponse, options)

Pushes a message to an agent.

put(url, body, contentType, options)

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().

readHistory(resourceType, id, options)

Reads resource history by resource type and ID.

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

readPatientEverything(id, options)

Executes the Patient "everything" operation for a patient.

readReference(reference, options)

Reads a resource by Reference.

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

readResource(resourceType, id, options)

Reads a resource by resource type and ID.

readResourceGraph(resourceType, id, graphName, options)

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

readVersion(resourceType, id, vid, options)

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

refreshIfExpired()

Refreshes the access token using the refresh token if available.

requestProfileSchema(profileUrl, options)

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

requestSchema(resourceType)

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

search(resourceType, query, options)

Sends a FHIR search request.

searchOne(resourceType, query, options)

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.

searchResourcePages(resourceType, query, options)

Creates an [async generator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/AsyncGenerator) over a series of FHIR search requests for paginated search results. Each iteration of the generator yields the array of resources on each page.

searchResources(resourceType, query, options)

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.

searchValueSet(system, filter, options)

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

sendEmail(email, options)

Sends an email using the Medplum Email API.

Builds the email using nodemailer MailComposer.

Examples:

setAccessToken(accessToken, refreshToken)

Sets the current access token.

setActiveLogin(login)

Sets the active login.

setBasicAuth(clientId, clientSecret)

Sets the client ID and secret for basic auth.

signInWithExternalAuth(authorizeUrl, clientId, redirectUri, baseLogin, pkceEnabled)

Initiates sign in with an external identity provider.

signInWithRedirect(loginParams)

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.

signOut()

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

signOutWithRedirect()

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

startAsyncRequest(url, options)

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

startClientLogin(clientId, clientSecret)

Starts a new OAuth2 client credentials flow.

startGoogleLogin(loginRequest, options)

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

startJwtAssertionLogin(jwt)

Starts a new OAuth2 JWT assertion flow.

See: https://datatracker.ietf.org/doc/html/rfc7523\#section-2.2

startJwtBearerLogin(clientId, assertion, scope)

Starts a new OAuth2 JWT bearer flow.

startLogin(loginRequest, options)

Initiates a user login flow.

startNewPatient(newPatientRequest, options)

Initiates a new patient flow.

This requires a partial login from startNewUser or startNewGoogleUser.

startNewProject(newProjectRequest, options)

Initiates a new project flow.

This requires a partial login from startNewUser or startNewGoogleUser.

startNewUser(newUserRequest, options)

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

startPkce()

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

subscribeToCriteria(criteria, subscriptionProps)

Subscribes to a given criteria, listening to notifications over WebSockets.

This uses Medplum's WebSocket Subscriptions under the hood.

A SubscriptionEmitter is returned from this function, which can be used to listen for updates to resources described by the given criteria.

When subscribing to the same criteria multiple times, the same SubscriptionEmitter will be returned, and a reference count will be incremented.

-----

unsubscribeFromCriteria(criteria, subscriptionProps)

Unsubscribes from the given criteria.

When called the same amount of times as proceeding calls to subscribeToCriteria on a given criteria, the criteria is fully removed from the SubscriptionManager.

updateResource(resource, options)

Updates a FHIR resource.

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

uploadMedia(contents, contentType, filename, additionalFields, options)

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

uploadwithProgress(url, data, contentType, onProgress, options)

upsertResource(resource, query, options)

Upsert a resource: update it in place if it exists, otherwise create it. This is done in a single, transactional request to guarantee data consistency.

validateResource(resource, options)

Executes the validate operation with the provided resource.

valueSetExpand(params, options)

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