### Basic Java Version Output Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/tools/hapi_fhir_cli.md Example output when Java is installed and the `java -version` command is executed. This confirms the Java runtime environment is available. ```text java version "1.8.0_60" Java(TM) SE Runtime Environment (build 1.8.0_60-b27) Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode) ``` -------------------------------- ### Complete Annotation Client Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/annotation_client.md A comprehensive example demonstrating the setup and usage of an annotation-driven FHIR client. ```java import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.OptionalParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.client.api.IGenericClient; import ca.uhn.fhir.rest.client.api.IRestfulClient; import ca.uhn.fhir.rest.param.DateRangeParam; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Patient; import org.hl7.fhir.r4.model.IdType; import java.util.List; public class CompleteExampleClient { // Define the client interface public interface MyFhirClient extends IRestfulClient { @Read Patient getPatientById(@IdParam IdType theId); @Search List findPatientsByDob(@OptionalParam(name = "birthdate") DateRangeParam theParam); @Search Bundle searchAllPatients(); } public static void main(String[] args) { // Create a FHIR context FhirContext ctx = FhirContext.forR4(); // Create an annotation-driven client instance MyFhirClient client = ctx.newRestfulClient(MyFhirClient.class); client.setServerBase("http://hapi.fhir.org/baseR4"); // Example: Get a patient by ID IdType patientId = new IdType("Patient", "123"); Patient patient = client.getPatientById(patientId); System.out.println("Retrieved patient: " + patient.getNameFirstRep().getGivenAsSingleString() + " " + patient.getNameFirstRep().getFamilyAsSingleString()); // Example: Find patients by date of birth range DateRangeParam dobRange = new DateRangeParam("1980-01-01", "1990-12-31"); List patients = client.findPatientsByDob(dobRange); System.out.println("Found " + patients.size() + " patients in the date range."); // Example: Search for all patients Bundle bundle = client.searchAllPatients(); System.out.println("Found " + bundle.getTotal() + " total patients."); } } ``` -------------------------------- ### Example Incoming Practitioner Resource Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa_mdm/mdm_rules.md An example of an incoming Practitioner resource used in MDM matching scenarios. ```json { "resourceType": "Practitioner", "id": "example", "identifier": [ { "system": "urn:oid:1.2.36.146.595.404.0.1", "value": "56789" } ], "name": [ { "family": "Smith", "given": ["Adam"] } ] } ``` -------------------------------- ### A Complete Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/annotation_client.md A comprehensive example illustrating the usage of an annotation-driven RESTful client with HAPI FHIR. ```APIDOC ## A Complete Example The following is a complete example showing a RESTful client using HAPI FHIR. ```java {{snippet:classpath:/ca/uhn/hapi/fhir/docs/CompleteExampleClient.java|client}} ``` ``` -------------------------------- ### Basic _content Search Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/elastic.md Demonstrates a basic HTTP GET request to search for resources containing specific terms using the `_content` parameter. ```http GET [base]/Observation?_content=cancer OR metastases OR tumor ``` -------------------------------- ### PlanDefinition Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/clinical_reasoning/plan_definitions.md An example of a PlanDefinition resource, illustrating its various components including triggers, conditions, dynamic values, and actions. ```json { "valueCodeableConcept": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/evidence-quality", "code": "low", "display": "Low quality" } ] } } ] } ], "trigger": [ { "type": "named-event", "name": "medication-prescribe" } ], "condition": [ { "kind": "applicability", "expression": { "description": "Check whether the opioid prescription for the existing patient is extended-release without any opioids-with-abuse-potential prescribed in the past 90 days.", "language": "text/cql-identifier", "expression": "Inclusion Criteria" } } ], "groupingBehavior": "visual-group", "selectionBehavior": "exactly-one", "dynamicValue": [ { "path": "action.title", "expression": { "language": "text/cql-identifier", "expression": "Get Summary" } }, { "path": "action.description", "expression": { "language": "text/cql-identifier", "expression": "Get Detail" } }, { "path": "activity.extension", "expression": { "language": "text/cql-identifier", "expression": "Get Indicator" } } ], "action": [ { "description": "Will prescribe immediate release" }, { "description": "Risk of overdose carefully considered and outweighed by benefit; snooze 3 mo" }, { "description": "N/A - see comment; snooze 3 mo" } ] } ] } ``` -------------------------------- ### MDM Query Links GET Request with Pagination Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa_mdm/mdm_operations.md Example of how to query MDM links using a GET request with pagination parameters. ```http GET http://example.com/$mdm-query-links?_offset=0&_count=2 ``` -------------------------------- ### MDM Query Links Sort Specification Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa_mdm/mdm_operations.md Example URL demonstrating how to specify sorting parameters for the $mdm-query-links operation, including descending order. ```url http://example.com/$mdm-query-links?_sort=-myScore,myCreated ``` -------------------------------- ### Simple FHIRPath Examples Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/fhir_patch.md Examples of simple FHIRPath expressions used for navigating resource structures. ```fhirpath Patient.birthDate ``` ```fhirpath Patient.name.family ``` ```fhirpath Observation.code.coding ``` -------------------------------- ### Observation Resource Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/elastic.md An example of an Observation resource, illustrating the structure and data that can be indexed for full-text search. ```json { "resourceType" : "Observation", "code" : { "coding" : [{ "system" : "http://loinc.org", "code" : "15074-8", "display" : "Glucose [Moles/volume] in Blood Found during patient's visit!" }] } "valueQuantity" : { "value" : 6.3, "unit" : "mmol/l", "system" : "http://unitsofmeasure.org", "code" : "mmol/L" } } ``` -------------------------------- ### Example Incoming Patient Resource Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa_mdm/mdm_rules.md An example of an incoming Patient resource that would be used in conjunction with MDM rules. ```json { "resourceType": "Patient", "id": "example", "identifier": [ { "system": "urn:oid:1.2.36.146.595.217.0.1", "value": "12345" } ], "name": [ { "family": "Chalmers", "given": ["Peter", "James"] } ] } ``` -------------------------------- ### Create Resource Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/generic_client.md Provides an example of how to perform a standard resource create operation using the generic client. ```APIDOC # Create - Type The following example shows how to perform a create operation using the generic client: ```java // Java code snippet for creating a resource ``` ``` -------------------------------- ### Simple Interceptor Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/interceptors/interceptors.md A basic example demonstrating the structure of an interceptor class with a hook method. ```java package ca.uhn.fhir.docs; import ca.uhn.fhir.interceptor.api.Hook; import ca.uhn.fhir.interceptor.api.Interceptor; import ca.uhn.fhir.interceptor.api.Pointcut; import ca.uhn.fhir.rest.api.server.RequestDetails; @Interceptor public class SampleInterceptor { @Hook(Pointcut.SERVER_INCOMING_REQUEST_PRE_HANDLED) public void preHandle( RequestDetails theRequestDetails) { System.out.println("Handling request: " + theRequestDetails.getUriPrefix()); } } ``` -------------------------------- ### Upload Example Resources to Server Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/tools/hapi_fhir_cli.md Uploads a set of FHIR example resources to a specified HAPI FHIR server. This is useful for populating a test server with data. Ensure the server is running before executing. ```bash hapi-fhir-cli upload-examples -v dstu3 -t http://localhost:8080/baseDstu3 ``` -------------------------------- ### Menu Navigation Example Source: https://github.com/hapifhir/hapi-fhir/wiki/Writing-Documentation Illustrates the syntax for referencing menu navigation paths. The ' -> ' will be rendered as a stylized chevron. ```text File -> Options -> Add File... ``` -------------------------------- ### Execute HFQL Query via GET (Link) Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-testpage-overlay/src/main/webapp/WEB-INF/templates/hfql.html Handles the click event for the 'Copy Link' button. It retrieves the HFQL query from the editor, sets up a form for GET submission to the 'hfql' endpoint, and submits the query to generate a shareable link. ```javascript let btn = $(this); handleActionButtonClick(btn); let value = editor.getValue(); btn.append($('', { type: 'hidden', name: 'hfql-query', value: value })); $("#outerForm").attr("method", "get"); $("#outerForm").attr("action", "hfql").submit(); ``` -------------------------------- ### Handling Includes in a Bundle (Java) Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/model/references.md Example of how to add an Organization resource to a bundle as an included resource, ensuring it appears as a distinct entry. ```java {{snippet:classpath:/ca/uhn/hapi/fhir/docs/IncludesExamples.java|addIncludes}} ``` -------------------------------- ### Unsupported _has Chain Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/search.md This example demonstrates a search chain within _has that is not currently supported by the HAPI FHIR JPA Server for performance reasons. ```http https://localhost:8000/Practitioner?_has:PractitionerRole:practitioner:service.type=CHIRO ``` -------------------------------- ### Plain Provider Example (Java) Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_plain/resource_providers.md A HAPI FHIR Plain Provider example. This provider defines a custom operation for multiple resource types, explicitly specifying the resource type in the annotation when returning a Bundle. ```java public class ExampleProviders { // This is a Plain Provider, so it does not implement IResourceProvider public static class ExamplePlainProvider { /** * This is an example of a "read" operation that returns a Bundle. * Since it returns a Bundle, we need to specify the resource type it applies to. */ @Read(type = "Patient") public Bundle getPatientBundle(@IdParam IdType theId) { // ... implementation omitted ... return new Bundle(); } /** * This is an example of a "history" operation that applies to the entire server. * It does not need a type specified, as it is a server-level operation. */ @History public Bundle getServerHistory() { // ... implementation omitted ... return new Bundle(); } } // This is a Plain Provider, so it does not implement IResourceProvider public static class ExamplePlainProviderServer { /** * This is an example of a "read" operation that returns a Bundle. * Since it returns a Bundle, we need to specify the resource type it applies to. */ @Read(type = "Patient") public Bundle getPatientBundle(@IdParam IdType theId) { // ... implementation omitted ... return new Bundle(); } /** * This is an example of a "history" operation that applies to the entire server. * It does not need a type specified, as it is a server-level operation. */ @History public Bundle getServerHistory() { // ... implementation omitted ... return new Bundle(); } } } ``` -------------------------------- ### Basic Authorization Rules Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/security/authorization_interceptor.md Subclass AuthorizationInterceptor to implement basic access rules for patients and administrators. ```java public class MyAuthorizationInterceptor extends AuthorizationInterceptor { @Override public List buildRuleList(@Nonnull RequestDetails theRequest) { return new RuleBuilder() .allowAllDefaultResponseMethods() .patient(theRequest) .readWriteAccess("Observation", "MedicationOrder") .compartment("Patient") .and() .admin(theRequest) .allowAllResources() .build(); } } ``` -------------------------------- ### RestfulServer Servlet Example (Java) Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_plain/resource_providers.md Example of creating a HAPI FHIR server by extending RestfulServer. This class is a specialized Java Servlet used to host resource and plain providers. ```java public class ExampleRestfulServlet extends RestfulServer { @Override protected void configure() { // Configure the server setFhirVersion(FhirVersionEnum.R4); setImplementationDesc("HAPI FHIR R4 Server"); // -- Register Providers -- // Resource Providers setResourceProviders(Arrays.asList( new RestfulPatientResourceProvider(new Dao()), new RestfulOrganizationResourceProvider(new Dao()) )); // Plain Providers setPlainProviders(Collections.singletonList( new ExamplePlainProvider() )); } } ``` -------------------------------- ### Configure Candidate Search Parameters Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa_mdm/mdm_rules.md Define the primary search parameters for candidate resources. This example includes Patient and Practitioner resources. ```json { "candidateSearchParams": [ { "resourceType": "Patient", "searchParams": ["given", "family"] }, { "resourceType": "Practitioner", "searchParam": "email" } ] } ``` -------------------------------- ### Retrospective Use Case Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/clinical_reasoning/caregaps.md Example of a GET request to identify closed care gaps retrospectively. ```APIDOC ## GET $care-gaps ### Description Retrieves a Gaps in Care Report for a specified period and subject, identifying closed gaps. ### Method GET ### Endpoint /fhir/Measure/$care-gaps ### Query Parameters - **periodStart** (date) - Required - The start date of the reporting period. - **periodEnd** (date) - Required - The end date of the reporting period. - **subject** (string) - Required - The patient resource ID for whom the report is generated. - **measureId** (string) - Required - The ID of the quality measure to evaluate. - **status** (string) - Optional - Filters the report to include only gaps with the specified status (e.g., 'closed-gap'). ### Request Example ``` GET http://localhost/fhir/Measure/$care-gaps?periodStart=2020-01-01&periodEnd=2020-12-31&subject=Patient/end-to-end-EXM130&measureId=ColorectalCancerScreeningsFHIR&status=closed-gap ``` ### Response #### Success Response (200) - The response will contain a FHIR Bundle resource detailing the Gaps in Care Report, including identified closed gaps. ``` -------------------------------- ### Prospective Use Case Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/clinical_reasoning/caregaps.md Example of a GET request to identify open care gaps prospectively. ```APIDOC ## GET $care-gaps ### Description Retrieves a Gaps in Care Report for a specified period and subject, identifying open gaps. ### Method GET ### Endpoint /fhir/Measure/$care-gaps ### Query Parameters - **periodStart** (date) - Required - The start date of the reporting period. - **periodEnd** (date) - Required - The end date of the reporting period. - **subject** (string) - Required - The patient resource ID for whom the report is generated. - **measureId** (string) - Required - The ID of the quality measure to evaluate. - **status** (string) - Optional - Filters the report to include only gaps with the specified status (e.g., 'open-gap'). ### Request Example ``` GET http://localhost/fhir/Measure/$care-gaps?periodStart=2020-01-01&periodEnd=2020-12-31&subject=Patient/end-to-end-EXM130&measureId=ColorectalCancerScreeningsFHIR&status=open-gap ``` ### Response #### Success Response (200) - The response will contain a FHIR Bundle resource detailing the Gaps in Care Report, including identified open gaps. ``` -------------------------------- ### JAX-RS Conformance Provider Setup Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_plain/jax_rs.md Illustrates how to set up a conformance provider to export the server's conformance statements, typically called during PostConstruct. ```java public class JaxRsConformanceProvider extends AbstractJaxRsConformanceProvider { private Collection providers; @PostConstruct public void initialize() { // This method is called once during server startup providers = new ArrayList<>(); providers.add(new JaxRsPatientRestProvider()); // Add other providers here } @Override public Collection getProviders() { return providers; } } ``` -------------------------------- ### Initialize Test Page Options Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-testpage-overlay/src/main/webapp/WEB-INF/templates/tmpl-navbar-left.html Sets up the initial state of encoding, pretty printing, and summary options based on URL parameters. It also handles updating the URL when these options are changed on a result page. ```javascript $( document ).ready(function() { // Encoding buttons are wider, so set the shorter group to the same width // so that they wrap at the same time if the page is narrow $('#prettyBtnGroup').width($('#encodingBtnGroup').width()); var encoding = [[${encoding}]]; if (encoding == 'xml') { $('#encode-xml').trigger("click"); } else if (encoding == 'json') { $('#encode-json').trigger("click"); } var pretty = [[${pretty}]]; if (pretty){ $('#pretty-true').trigger("click"); } else { $('#pretty-false').trigger("click"); } var summary = [[${_summary}]]; if (summary == 'true') { $('#summary-true').trigger("click"); } else if (summary == 'text') { $('#summary-text').trigger("click"); } else if (summary == 'data') { $('#summary-data').trigger("click"); } else if (summary == 'count') { $('#summary-count').trigger("click"); } else { $('#summary-default').trigger("click"); } const hasResultBody = [[${!#strings.isEmpty(resultBody)}]]; if (hasResultBody) { // When we're displaying a result page, the options buttons should // actually apply their values to the current search/action $('#encode-default').change(function(){ if (hasResultBody) location.href=updateURLParameter(location.href, 'encoding', ''); }); $('#encode-xml').change(function(){ location.href=updateURLParameter(location.href, 'encoding', 'xml'); }); $('#encode-json').change(function(){ location.href=updateURLParameter(location.href, 'encoding', 'json'); }); $('#pretty-default').change(function(){ location.href=updateURLParameter(location.href, 'pretty', ''); }); $('#pretty-true').change(function(){ location.href=updateURLParameter(location.href, 'pretty', 'true'); }); $('#pretty-false').change(function(){ location.href=updateURLParameter(location.href, 'pretty', 'false'); }); } }); ``` -------------------------------- ### Create Composition and Generate Document Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/examples.md This example demonstrates how to create a Composition resource with linked resources and then use the server's $document operation to generate a document. ```java /*- * The MIT License * * Copyright (c) 2010-2024 Google, Inc. * Copyright (c) 2010-2024 OpenMRS, LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package ca.uhn.hapi.fhir.docs; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.client.api.IGenericClient; import org.hl7.fhir.r4.model.Bundle; import org.hl7.fhir.r4.model.Composition; import org.hl7.fhir.r4.model.DocumentReference; import org.hl7.fhir.r4.model.IdType; import org.hl7.fhir.r4.model.Narrative; import org.hl7.fhir.r4.model.Reference; import org.hl7.fhir.r4.model.Resource; import org.hl7.fhir.r4.model.codesystems.CompositionStatus; import java.util.Date; public class CreateCompositionAndGenerateDocument { public static void main(String[] args) { // Create a FHIR context FhirContext ctx = FhirContext.forR4(); // Create a client // Replace with your server URL String serverBase = "http://hapi.fhir.org/baseR4"; IGenericClient client = ctx.newRestfulGenericClient(serverBase); // Create a Composition resource Composition composition = new Composition(); composition.setStatus(CompositionStatus.FINAL); composition.setDate(new Date()); composition.setTitle("My Document"); composition.setConfidentiality("N, Confidential"); // Add a narrative Narrative narrative = new Narrative(); narrative.setStatus(Narrative.NarrativeStatus.GENERATED); narrative.setDivAsString( "

This is the narrative for my document.

"); composition.setText(narrative); // Create a DocumentReference resource to link DocumentReference docRef = new DocumentReference(); docRef.setType( new org.hl7.fhir.r4.model.CodeableConcept( new org.hl7.fhir.r4.model.Coding( "http://example.org/document-type", "progress-note", "Progress Note"))); docRef.setCreated(new Date()); docRef.setDescription("This is a progress note."); // Link the DocumentReference to the Composition composition.addSection() .setFocus(new Reference(docRef)) .setSection(new org.hl7.fhir.r4.model.CodeableConcept( new org.hl7.fhir.r4.model.Coding( "http://example.org/document-section", "progress-note-section", "Progress Note Section"))); // Create a Bundle containing the Composition and DocumentReference // The DocumentReference must be included in the bundle for the $document operation Bundle bundle = new Bundle(); bundle.setType(Bundle.BundleType.TRANSACTION); bundle.addEntry().setResource(composition); bundle.addEntry().setResource(docRef); // Create a Composition resource Composition composition2 = new Composition(); composition2.setStatus(CompositionStatus.FINAL); composition2.setDate(new Date()); composition2.setTitle("My Second Document"); composition2.setConfidentiality("N, Confidential"); // Add a narrative Narrative narrative2 = new Narrative(); narrative2.setStatus(Narrative.NarrativeStatus.GENERATED); narrative2.setDivAsString( "

This is the narrative for my second document.

"); composition2.setText(narrative2); // Create a DocumentReference resource to link DocumentReference docRef2 = new DocumentReference(); docRef2.setType( new org.hl7.fhir.r4.model.CodeableConcept( new org.hl7.fhir.r4.model.Coding( "http://example.org/document-type", "progress-note", "Progress Note"))); docRef2.setCreated(new Date()); docRef2.setDescription("This is a second progress note."); // Link the DocumentReference to the Composition composition2.addSection() .setFocus(new Reference(docRef2)) .setSection(new org.hl7.fhir.r4.model.CodeableConcept( new org.hl7.fhir.r4.model.Coding( "http://example.org/document-section", "progress-note-section", "Progress Note Section"))); // Create a Bundle containing the Composition and DocumentReference // The DocumentReference must be included in the bundle for the $document operation Bundle bundle2 = new Bundle(); bundle2.setType(Bundle.BundleType.TRANSACTION); bundle2.addEntry().setResource(composition2); bundle2.addEntry().setResource(docRef2); // Call the $document operation // The server will return a Bundle containing the generated document // The Bundle will contain the Composition and all linked resources Bundle responseBundle = client.operation() .onServer() .named("$document") .withParameter(Composition.class.getSimpleName(), composition) .execute(); // Process the response bundle System.out.println("Generated Document Bundle:"); for (Bundle.EntryComponent entry : responseBundle.getEntry()) { System.out.println(" - " + entry.getResource().getIdElement()); } // Call the $document operation with a different composition Bundle responseBundle2 = client.operation() .onServer() .named("$document") .withParameter(Composition.class.getSimpleName(), composition2) .execute(); // Process the response bundle System.out.println("Generated Second Document Bundle:"); for (Bundle.EntryComponent entry : responseBundle2.getEntry()) { System.out.println(" - " + entry.getResource().getIdElement()); } } } ``` -------------------------------- ### Evaluate Measure with Reporting Period Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/clinical_reasoning/measures.md This example demonstrates how to call the $evaluate-measure operation with specific reporting period start and end dates. ```APIDOC ## GET fhir/Measure/{MeasureId}/$evaluate-measure ### Description Evaluates a measure for a specified reporting period. ### Method GET ### Endpoint fhir/Measure/{MeasureId}/$evaluate-measure ### Query Parameters - **periodStart** (date or datetime) - Required - The start date/datetime of the reporting period. - **periodEnd** (date or datetime) - Required - The end date/datetime of the reporting period. ### Request Example ```bash GET fhir/Measure/?periodStart=2019-01-01&periodEnd=2019-12-31 ``` ### Notes - `periodStart` and `periodEnd` must be used together or not at all. - If neither is used, the default reporting period from the CQL logic is applied. - Supported date formats: YYYY, YYYY-MM, YYYY-MM-DD. Supported datetime formats: YYYY-MM-DDThh:mm:ss. - Timezone information should be passed via headers as described in the [Headers](#headers) section. ``` -------------------------------- ### $mdm-query-links Operation Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa_mdm/mdm_operations.md This operation allows querying for MDM links between resources. It can be invoked via HTTP GET or POST. The example shows how to find possible matches. ```APIDOC ## $mdm-query-links Operation ### Description Use an HTTP GET or POST to query for MDM links. This operation can filter links based on match results and supports pagination. ### Method GET or POST ### Endpoint `http:///$mdm-query-links` ### Query Parameters - **_offset** (integer) - Optional - The starting offset for the query. - **_count** (integer) - Optional - The number of results to return. - **matchResult** (string) - Optional - Filters links by match result (e.g., POSSIBLE_MATCH). ### Request Body ```json { "resourceType": "Parameters", "parameter": [ { "name": "prev", "valueUri": "http://example.com/$mdm-query-links?_offset=8&_count=2" }, { "name": "self", "valueUri": "http://example.com/$mdm-query-links?_offset=10&_count=2" }, { "name": "next", "valueUri": "http://example.com/$mdm-query-links?_offset=12&_count=2" }, { "name": "matchResult", "valueString": "POSSIBLE_MATCH" } ] } ``` ### Response #### Success Response (200) Returns a `Parameters` resource containing links and pagination information. #### Response Example ```json { "resourceType": "Parameters", "parameter": [ { "name": "prev", "valueUri": "http://example.com$mdm-query-links?_offset=8&_count=2" }, { "name": "self", "valueUri": "http://example.com$mdm-query-links?_offset=10&_count=10" }, { "name": "next", "valueUri": "http://example.com$mdm-query-links?_offset=20&_count=10" }, { "name": "link", "part": [ { "name": "goldenResourceId", "valueString": "Patient/123" }, { "name": "sourceResourceId", "valueString": "Patient/456" }, { "name": "matchResult", "valueString": "POSSIBLE_MATCH" }, { "name": "linkSource", "valueString": "AUTO" }, { "name": "eidMatch", "valueBoolean": false }, { "name": "hadToCreateNewResource", "valueBoolean": false }, { "name": "score", "valueDecimal": 1.8 } ] } ] } ``` ``` -------------------------------- ### Install HAPI FHIR CLI with Homebrew Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/tools/hapi_fhir_cli.md Installs the HAPI FHIR CLI tool on macOS using the Homebrew package manager. Ensure Homebrew is installed before running this command. ```bash brew install hapi-fhir-cli ``` -------------------------------- ### Create Generic Client and Perform Operations Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/generic_client.md Demonstrates how to instantiate a FhirContext and a generic client, along with performing basic operations. Remember that FhirContext is expensive to create and should be reused. ```java //@formatter:off public class GenericClientExample { public static void main(String[] args) throws Exception { // The FhirContext is expensive to create, so you should keep it around for the // lifetime of your application. It is thread-safe. FhirContext ctx = FhirContext.forR4(); // The client is inexpensive to create, and can be created per-request if needed. // It is also thread-safe. IGenericClient client = ctx.newRestfulGenericClient("http://hapi.fhir.org/baseR4"); // Read a resource by ID Patient patient = client.read().resource(Patient.class).withId("123").execute(); // Create a resource Patient newPatient = new Patient(); newPatient.addIdentifier().setSystem("urn:mrns:example").setValue("12345"); newPatient.addName().addFamily("Test") .addGiven("Testy"); IIdType id = client.create().resource(newPatient).execute().getId(); System.out.println("Created patient with ID: " + id); // Update a resource patient.addName().addGiven("Robert"); client.update().resource(patient).execute(); // Delete a resource client.delete().resourceById("Patient", "123").execute(); } } //@formatter:on ``` -------------------------------- ### Example Quantity Value Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/schema.md Example of a quantity value in FHIR JSON format. ```json "valueQuantity" : { "value" : 172, "unit" : "lb_av", "system" : "http://unitsofmeasure.org", "code" : "[lb_av]" } ``` -------------------------------- ### Install FHIR Package using PackageInstallationSpec Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/packages.md Install a FHIR NPM package from the FHIR NPM package registry using the `PackageInstallationSpec` Java API. Set `fetchDependencies` to true to recursively install all transitive dependencies. ```java PackageInstallationSpec spec = new PackageInstallationSpec() .setName("hl7.fhir.us.core") .setVersion("7.0.0") .setInstallMode(PackageInstallationSpec.InstallModeEnum.STORE_AND_INSTALL) .setFetchDependencies(true); myPackageInstallerSvc.install(spec); ``` -------------------------------- ### Partitioning by Resource Contents Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa_partitioning/partition_interceptor_examples.md Factors the resource's content into the partition decision. This example places resources into partitions based on their type, demonstrating flexibility beyond request metadata. ```java public class PartitionInterceptorResourceContents extends PartitionInterceptor { @Override public void partition(RequestDetails theRequest, PartitionMetadata thePartitionMetadata) { String resourceType = theRequest.getResourceType(); if ("Patient".equals(resourceType)) { thePartitionMetadata.setPartitionId("partition-patients"); } else if ("Observation".equals(resourceType)) { thePartitionMetadata.setPartitionId("partition-observations"); } else { thePartitionMetadata.setPartitionId("partition-other"); } } } ``` -------------------------------- ### Example Quantity Search URL Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_plain/rest_operations_search.md Illustrates how to invoke a method that accepts quantity search parameters, including units and a specific URL for the unit. ```url http://fhir.example.com/Observation?value-quantity=lt123.2||mg|http://unitsofmeasure.org ``` -------------------------------- ### Measure Scoring Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/clinical_reasoning/measures.md An example FHIR Measure resource demonstrating the 'scoring' element set to 'proportion'. ```json { "resourceType": "Measure", "scoring": { "coding": [ { "system": "http://terminology.hl7.org/CodeSystem/measure-scoring", "code": "proportion", "display": "Proportion" } ] } } ``` -------------------------------- ### Custom Bundle Provider Implementation Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_plain/paging.md This example shows a custom implementation of IBundleProvider. This provider strategy optimizes memory usage by only keeping resource IDs in memory and fetching resources as needed. ```java public class PagingPatientProvider implements IBundleProvider { private List myPatientIds; public PagingPatientProvider(List thePatientIds) { myPatientIds = thePatientIds; } @Override public List getResources(int theFromIndex, int theToIndex) { // Fetch resources based on the requested range of IDs // ... implementation details ... return null; // Placeholder } @Override public int size() { return myPatientIds.size(); } @Override public Date getLastUpdated() { return new Date(); // Placeholder } @Override public Integer getWidth() { return null; } } ``` -------------------------------- ### Example Observation Index Document Source: https://github.com/hapifhir/hapi-fhir/wiki/Design-Proposal-for-Observation-lastn-Operation An example of a generated index document for an Observation, illustrating the structure and data. ```json { "identifier" : "093d5af6-7347-482a-aa32-53814767d85e", "subject" : "Patient/0000039a-636f-45eb-97aa-85582d8e9805", "category" : [ { "code_system_hash" : [ 950854891576463190 ] } ], "status" : "Final", "code" : [ { "code_system_hash" : 7417299403646902754 } ], "normalized_code" : "7417299403646902754", "interpretation" : { "code_system_hash" : [ -1469111858374900926 ] }, "bodysite" : { "code_system_hash" : [ 4376320339240164549 ] }, "method" : { "code_system_hash" : [ 5670388653210975895 ] }, "effectivedtm" : 1569349466169, "metatag" : -5313397126116324049 } ``` -------------------------------- ### Run Server with Maven Jetty Plugin Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_plain/introduction.md Execute the Maven Jetty Plugin to compile and deploy your code to a local server for easy testing. This requires no additional installation. ```bash mvn jetty:run ``` -------------------------------- ### Instantiating the Client Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/annotation_client.md Demonstrates how to instantiate an annotation-driven FHIR client after defining the client interface, using FhirContext. ```APIDOC ## Instantiating the Client Once your client interface is created, all that is left is to create aFhirContext and instantiate the client and you are ready to start using it. ```java {{snippet:classpath:/ca/uhn/hapi/fhir/docs/ExampleRestfulClient.java|client}} ``` ``` -------------------------------- ### Transaction Response Example Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/examples.md Example of a server response to a transaction, indicating the status and location of created or updated resources. ```xml ``` -------------------------------- ### Creating a Patient Resource with a Managing Organization Reference (Java) Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/model/references.md Demonstrates how to create a Patient resource in Java and set a reference to its managing organization. ```java Patient patient = new Patient(); patient.setId("Patient/1333"); patient.addIdentifier("urn:mrns", "253345"); patient.getManagingOrganization().setReference("Organization/124362"); ``` -------------------------------- ### Install FHIR Package Asynchronously Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/server_jpa/packages.md Install a FHIR NPM package asynchronously using the `installAsynchronously` method with a pre-configured `PackageInstallationSpec`. ```java myPackageInstallerSvc.installAsynchronously(spec); ``` -------------------------------- ### Example QuestionnaireResponse Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/clinical_reasoning/questionnaires.md This is an example of a QuestionnaireResponse resource. It includes extensions, questionnaire reference, status, subject, and nested items with answers. ```json { "resourceType": "QuestionnaireResponse", "id": "ASLPA1-positive-response", "extension": [ { "url": "http://hl7.org/fhir/us/davinci-dtr/StructureDefinition/dtr-questionnaireresponse-questionnaire", "valueReference": { "reference": "#ASLPA1-positive" } } ], "questionnaire": "http://example.org/sdh/dtr/aslp/Questionnaire/ASLPA1", "status": "in-progress", "subject": { "reference": "Patient/positive" }, "item": [ { "linkId": "0", "definition": "http://example.org/sdh/dtr/aslp/StructureDefinition/aslp-sleep-study-order", "text": "A sleep study procedure being ordered", "item": [ { "extension": [ { "url": "http://hl7.org/fhir/StructureDefinition/questionnaireresponse-author", "valueReference": { "reference": "http://cqframework.org/fhir/Device/clinical-quality-language" } } ], "linkId": "1", "definition": "http://example.org/sdh/dtr/aslp/StructureDefinition/aslp-sleep-study-order#ServiceRequest.code", "text": "A sleep study procedure being ordered", "answer": [ { "valueCoding": { "system": "http://example.org/sdh/dtr/aslp/CodeSystem/aslp-codes", "code": "ASLP.A1.DE2", "display": "Home sleep apnea testing (HSAT)" } } ] }, { "extension": [ { "url": "http://hl7.org/fhir/StructureDefinition/questionnaireresponse-author", "valueReference": { "reference": "http://cqframework.org/fhir/Device/clinical-quality-language" } } ], "linkId": "2", "definition": "http://example.org/sdh/dtr/aslp/StructureDefinition/aslp-sleep-study-order#ServiceRequest.occurrence[x]", "text": "Date of the procedure", "answer": [ { "valueDateTime": "2023-04-10T08:00:00.000Z" } ] } ] }, { "linkId": "0", "definition": "http://example.org/sdh/dtr/aslp/StructureDefinition/aslp-sleep-study-order", "text": "A sleep study procedure being ordered", "item": [ { "extension": [ { "url": "http://hl7.org/fhir/StructureDefinition/questionnaireresponse-author", "valueReference": { "reference": "http://cqframework.org/fhir/Device/clinical-quality-language" } } ], "linkId": "1", "definition": "http://example.org/sdh/dtr/aslp/StructureDefinition/aslp-sleep-study-order#ServiceRequest.code", "text": "A sleep study procedure being ordered", "answer": [ { "valueCoding": { "system": "http://example.org/sdh/dtr/aslp/CodeSystem/aslp-codes", "code": "ASLP.A1.DE14", "display": "Artificial intelligence (AI)" } } ] }, { "extension": [ { "url": "http://hl7.org/fhir/StructureDefinition/questionnaireresponse-author", "valueReference": { "reference": "http://cqframework.org/fhir/Device/clinical-quality-language" } } ], "linkId": "2", "definition": "http://example.org/sdh/dtr/aslp/StructureDefinition/aslp-sleep-study-order#ServiceRequest.occurrence[x]", "text": "Date of the procedure", "answer": [ { "valueDateTime": "2023-04-15T08:00:00.000Z" } ] } ] }, { "extension": [ { "url": "http://hl7.org/fhir/StructureDefinition/questionnaireresponse-author", "valueReference": { "reference": "http://cqframework.org/fhir/Device/clinical-quality-language" } } ], "linkId": "3", "definition": "http://example.org/sdh/dtr/aslp/StructureDefinition/aslp-diagnosis-of-obstructive-sleep-apnea#Condition.code", "text": "Diagnosis of Obstructive Sleep Apnea", "answer": [ { "valueCoding": { ``` -------------------------------- ### Example BALP Audit Context Services Implementation Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/security/balp_interceptor.md Provides a basic implementation of the IBalpAuditContextServices interface, which is required for the BALP interceptor to gather necessary context information for audit events. ```java public class FhirTestBalpAuditContextServices implements IBalpAuditContextServices { @Override public IBalpAgent getAgent(HttpServletRequest theRequest) { // TODO Auto-generated method stub return null; } @Override public IBalpUser getUser(HttpServletRequest theRequest) { // TODO Auto-generated method stub return null; } } ``` -------------------------------- ### Deploy Site Source: https://github.com/hapifhir/hapi-fhir/wiki/Release-Process Deploys the project site using the 'SITE' profile. This command may fail with an 'Argument list too long' error. ```bash mvn -P SITE site-deploy ``` -------------------------------- ### Search with Composite Parameters Source: https://github.com/hapifhir/hapi-fhir/blob/master/hapi-fhir-docs/src/main/resources/ca/uhn/hapi/fhir/docs/client/generic_client.md Demonstrates how to search using composite parameters, which combine multiple individual parameters. This example searches for a composite date parameter. ```java //@formatter:off // Search for Patients with a composite date parameter (e.g., birthdate) // This example assumes a composite parameter is available and configured on the server // For demonstration, let's assume a hypothetical composite parameter 'birthdate-year-month' // The actual syntax for composite parameters depends on the specific FHIR resource and parameter definition. // Example using a hypothetical composite parameter: // Bundle resultsComposite = client.search() // .forResource(Patient.class) // .where(new CompositeParam("birthdate-year-month").left("1990").right("01")) // .execute(); // A more common scenario might involve searching by a specific date range for a single parameter: DatePartParam dateParam = new DatePartParam(); dateParam.setLow("2023-01-01").setHigh("2023-12-31"); Bundle resultsDateRange = client.search() .forResource(Observation.class) .where(Observation.PERFORMED.setQualifier(dateParam)) .execute(); //@formatter:on ```