Conditional update resource
Stay organized with collections
Save and categorize content based on your preferences.
Update the entire resource if the resource exists based on meeting the search criteria specified by using query parameters.
Code sample
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[[["\u003cp\u003eThe code examples demonstrate how to conditionally update FHIR resources in the Cloud Healthcare API using Go and Python.\u003c/p\u003e\n"],["\u003cp\u003eThe update is based on search criteria defined by query parameters, allowing you to target specific resources for modification.\u003c/p\u003e\n"],["\u003cp\u003eBoth examples show how to set up authentication and interact with the Cloud Healthcare API using the respective language's client libraries.\u003c/p\u003e\n"],["\u003cp\u003eThe provided Python code shows an example of updating observation resources, searching by a given identifier to update it to have a 'cancelled' status.\u003c/p\u003e\n"],["\u003cp\u003eThe provided Go code example provides a more granular approach to updating a FHIR resource, by setting query parameters to target resources updated within the last 48 hours.\u003c/p\u003e\n"]]],[],null,["# Conditional update resource\n\nUpdate the entire resource if the resource exists based on meeting the search criteria specified by using query parameters.\n\nCode sample\n-----------\n\n### Go\n\n\nBefore trying this sample, follow the Go setup instructions in the\n[Cloud Healthcare API quickstart using\nclient libraries](https://cloud.google.com/healthcare-api/docs/store-healthcare-data-client-library).\n\n\nFor more information, see the\n[Cloud Healthcare API Go API\nreference documentation](https://pkg.go.dev/google.golang.org/api/healthcare/v1).\n\n\nTo authenticate to Cloud Healthcare API, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n import (\n \t\"bytes\"\n \t\"context\"\n \t\"encoding/json\"\n \t\"fmt\"\n \t\"io\"\n \t\"time\"\n\n \thealthcare \"google.golang.org/api/healthcare/v1beta1\"\n )\n\n // queryParamOpt is a googleapi.Option (https://godoc.org/google.golang.org/api/googleapi#CallOption)\n // that adds query parameters to an API call.\n type queryParamOpt struct {\n \tkey, value string\n }\n\n func (qp queryParamOpt) Get() (string, string) { return qp.key, qp.value }\n\n // ConditionalUpdateFHIRResource conditionally updates an FHIR resource.\n func ConditionalUpdateFHIRResource(w io.Writer, projectID, location, datasetID, fhirStoreID, resourceType string, active bool) error {\n \t// projectID := \"my-project\"\n \t// location := \"us-central1\"\n \t// datasetID := \"my-dataset\"\n \t// fhirStoreID := \"my-fhir-store\"\n \t// resourceType := \"Patient\"\n \t// active := true\n\n \tctx := context.Background()\n\n \thealthcareService, err := healthcare.NewService(ctx)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"healthcare.NewService: %w\", err)\n \t}\n\n \tfhirService := healthcareService.Projects.Locations.Datasets.FhirStores.Fhir\n\n \tparent := fmt.Sprintf(\"projects/%s/locations/%s/datasets/%s/fhirStores/%s\", projectID, location, datasetID, fhirStoreID)\n\n \tpayload := map[string]interface{}{\n \t\t\"resourceType\": resourceType,\n \t\t\"active\": active,\n \t}\n \tjsonPayload, err := json.Marshal(payload)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"json.Encode: %w\", err)\n \t}\n\n \tcall := fhirService.ConditionalUpdate(parent, resourceType, bytes.NewReader(jsonPayload))\n\n \tcall.Header().Set(\"Content-Type\", \"application/fhir+json\")\n\n \t// Refine your search by appending tags to the request in the form of query\n \t// parameters. This searches for resources updated in the last 48 hours.\n \ttwoDaysAgo := time.Now().Add(-48 * time.Hour).Format(\"2006-01-02\")\n \tlastUpdated := queryParamOpt{key: \"_lastUpdated\", value: \"gt\" + twoDaysAgo}\n\n \tresp, err := call.Do(lastUpdated)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"ConditionalUpdate: %w\", err)\n \t}\n\n \tdefer resp.Body.Close()\n\n \trespBytes, err := io.ReadAll(resp.Body)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"could not read response: %w\", err)\n \t}\n\n \tif resp.StatusCode \u003e 299 {\n \t\treturn fmt.Errorf(\"ConditionalUpdate: status %d %s: %s\", resp.StatusCode, resp.Status, respBytes)\n \t}\n \tfmt.Fprintf(w, \"%s\", respBytes)\n\n \treturn nil\n }\n\n### Python\n\n\nBefore trying this sample, follow the Python setup instructions in the\n[Cloud Healthcare API quickstart using\nclient libraries](https://cloud.google.com/healthcare-api/docs/store-healthcare-data-client-library).\n\n\nFor more information, see the\n[Cloud Healthcare API Python API\nreference documentation](https://googleapis.github.io/google-api-python-client/docs/dyn/healthcare_v1).\n\n\nTo authenticate to Cloud Healthcare API, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n def conditional_update_resource(\n service_account_json,\n base_url,\n project_id,\n cloud_region,\n dataset_id,\n fhir_store_id,\n patient_id,\n encounter_id,\n ):\n \"\"\"\n If a resource is found based on the search criteria specified in\n the query parameters, updates the entire contents of that resource.\n \"\"\"\n url = f\"{base_url}/projects/{project_id}/locations/{cloud_region}\"\n\n # The search query in this request updates all Observations\n # using the Observation's identifier (ABC-12345 in my-code-system)\n # so that their 'status' is 'cancelled'.\n resource_path = \"{}/datasets/{}/fhirStores/{}/fhir/Observation\".format(\n url, dataset_id, fhir_store_id\n )\n\n # Make an authenticated API request\n session = get_session(service_account_json)\n\n body = {\n \"resourceType\": \"Observation\",\n \"status\": \"cancelled\",\n \"subject\": {\"reference\": f\"Patient/{patient_id}\"},\n \"effectiveDateTime\": \"2020-01-01T00:00:00+00:00\",\n \"code\": {\n \"coding\": [\n {\n \"system\": \"http://loinc.org\",\n \"code\": \"8867-4\",\n \"display\": \"Heart rate\",\n }\n ]\n },\n \"valueQuantity\": {\"value\": 55, \"unit\": \"bpm\"},\n \"encounter\": {\"reference\": f\"Encounter/{encounter_id}\"},\n }\n\n headers = {\"Content-Type\": \"application/fhir+json;charset=utf-8\"}\n\n params = {\"identifier\": \"my-code-system|ABC-12345\"}\n\n response = session.put(resource_path, headers=headers, params=params, json=body)\n\n response.raise_for_status()\n resource = response.json()\n\n print(\n \"Conditionally updated Observations with the identifier \"\n \"'my-code-system|ABC-12345' to have a 'status' of \"\n \"'cancelled'.\"\n )\n print(json.dumps(resource, indent=2))\n\n return resource\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=healthcare)."]]