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 EventTarget
Extends: EventTarget
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 |
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(data, filename, contentType, onProgress, options) | Creates a FHIR This is a convenience method for creating a The A | |
createBinary(data, filename, contentType, onProgress, options) | Creates a FHIR The return value is the newly created resource, including the ID and meta. The A | |
createComment(resource, text, options) | Creates a FHIR This is a convenience method to handle commmon cases where a | |
createPdf(docDefinition, filename, tableLayouts, fonts) | Creates a PDF as a FHIR The return value is the newly created resource, including the ID and meta. The | |
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(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 | |
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 | |
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. | |
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. | |
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(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 | |
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 | |
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 This is a convenience method for | |
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) | 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 | |
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 | |
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 | |
startNewProject(newProjectRequest, options) | Initiates a new project flow. This requires a partial login from | |
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. | |
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) | ||
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 |