Using Apigee with the Cloud Healthcare API

Last reviewed 2022-03-08 UTC

The Cloud Healthcare API is a fully managed, enterprise-scale Fast Healthcare Interoperability Resources (FHIR) datastore for your healthcare data that meets industry-specific security, privacy, and compliance requirements. It has a fully compliant FHIR datastore and FHIR API. The service lets you run AI and ML algorithms against your data to build intelligent healthcare solutions.

This tutorial shows you how to connect Apigee with the Cloud Healthcare API. It assumes that you have working knowledge of Apigee, the Cloud Healthcare API, and FHIR (pronounced fire). Read this tutorial if you're an API developer responsible for designing and implementing FHIR-based solutions.

Apigee lets enterprises design, secure, analyze, and scale APIs anywhere with visibility and control. It has the following two components:

  • Apigee Runtime, which enables enterprise-wide API management.
  • Developer portal, which enables you to onboard API consumers and to publish API documentation. For example, Developer portal lets developers register their FHIR apps. It can also host interactive FHIR API documentation.

The Cloud Healthcare API specializes in FHIR data. However, it doesn't have built-in API-management capabilities. Apigee lets you expose FHIR APIs in a controlled, secure way that aligns with the rest of your organization's APIs.

Architecture

Typical consumers for Cloud Healthcare API data include web applications, system-to-system connections, and mobile device applications. The following high-level diagram shows an API consumer calling the Apigee FHIR API proxy to retrieve patient data from Cloud Healthcare API.

Architecture diagram

Objectives

  • Create and deploy a shared flow that holds common configuration values.
  • Create and deploy an API proxy that can connect to Cloud Healthcare API and retrieve patient FHIR data.
  • Create and deploy a basic OAuth 2.0 client credentials API proxy.
  • Create an API product configuration.
  • Create a developer profile and a developer application configuration.
  • Test the API with cURL.
  • Learn about other Apigee features.

Costs

This tutorial uses the following non-billable components of Google Cloud:

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use the pricing calculator. New Google Cloud users might be eligible for a free trial.

When you finish the tasks that are described in this document, you can avoid continued billing by deleting the resources that you created. For more information, see Clean up.

Before you begin

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  2. Make sure that billing is enabled for your Google Cloud project.

  3. Provision an Apigee trial instance by following the Apigee provisioning instructions. You can also use an existing Apigee paid instance.
  4. Create a Cloud Healthcare API dataset and datastore.
  5. Generate sample R4 FHIR data.
  6. Load the data into the datastore.
  7. Create a service account in the same Google Cloud project as the Apigee instance. Add the following roles to the service account.

    1. Service account name: healthcareapi-sa
    2. Roles:
      1. FHIR store viewer
      2. FHIR resource editor
    3. If your Cloud Healthcare API instance is in a different Google Cloud project than the Apigee instance, add the service account to the project through IAM.

    The API proxy uses the service account to connect to the Cloud Healthcare API.

Create a common configuration shared flow

The shared flow you create in this section holds common configuration values. Once you create the shared flow, other proxies can use it.

  1. From the Apigee menu, in the Develop section, select Shared Flows. Click Create New.
  2. Name the shared flow common-config. Click Create.
  3. Click the Develop tab. Click the icon in the Policies section. Select Assign Message from the list.
  4. Set the name to AM-ConfigValues. Click Add, as shown in the following image.

    Common configuration options.

  5. Click the AM-ConfigValues policy. Copy and paste the following XML code:

       <AssignMessage continueOnError="false" enabled="true" name="AM-ConfigValues">
        <DisplayName>AM-ConfigValues</DisplayName>
        <AssignVariable>
            <Name>gcp.scopes</Name>
            <Value>https://www.googleapis.com/auth/cloud-platform</Value>
        </AssignVariable>
        <AssignVariable>
            <Name>gcp.healthcareapi-path</Name>
            <Value>projects/PROJECT_ID/locations/REGION/datasets/DATASET_NAME/fhirStores/FHIRSTORE_NAME</Value>
        </AssignVariable>
        <AssignVariable>
            <Name>gcp.proxy-domain</Name>
            <Value>api.domain.com</Value>
        </AssignVariable>
        <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
        <AssignTo createNew="false" transport="http" type="request"/>
    </AssignMessage>
    
    1. Populate the gcp.healthcareapi-path with the full path to your Cloud Healthcare API datastore. The path is listed in the Datastore details section of the Cloud Healthcare API datastore.
    2. Populate the gcp.proxy-domain with the domain name containing your API endpoint. The domain name was configured during the provisioning of the Apigee instance—for example, api.company.com or api.subdomain.company.com, as shown in the following image.

      Add API endpoint information.

  6. To add the policy to the default shared flow, click default in the Shared Flows section. Drag the AM-ConfigValues policy to the empty space in the flow, as shown in the following image.

    Drag and drop the AM-ConfigValues policy.

  7. Click Save to save the shared flow.

  8. To deploy the shared flow, click the Deploy drop-down button, and then click the Deploy {Version} button next to the environment.

    Deploying the shared flow makes it available to the FHIR API proxy.

Create an FHIR API proxy

In this section, you use the Apigee API management tool to create an FHIR API proxy that exposes Cloud Healthcare FHIR resources. An API proxy makes the FHIR data available through your chosen domain and path. You also add additional logic that secures and manages the API calls.

  1. From the Apigee menu, in the Develop section, select API Proxies. Click Create New.
  2. Select Reverse Proxy. Use the following values:
    • Name: fhir-r4-api-v1
    • Base path: /v1/fhir/r4
    • Target: https://healthcare.googleapis.com/v1/{gcp.healthcareapi-path}/fhir
    • Security: Authorization: OAuth 2.0: Select
    • Security: Browser: Add CORS Headers: Select
  3. Click Create to create the proxy. Click Edit Proxy to see the proxy's edit page.
  4. Click the icon next to the Policies section to create a shared flow policy to reference the common-config shared flow you created previously.

    • Select FlowCallout. Enter the following details and select common-config from the list:
      • FlowCallout:
        • Name: FC-Common-Config
        • Shared Flow: common-config
  5. Drag the FC-Common-Config policy to the default PreFlow proxy endpoint so it appears after the Remove Header Authorization policy, as shown in the following image.

    Drag and drop the FC-Common-Config policy.

When the Cloud Healthcare API returns FHIR data, the data contains references to internal URLs. The proxy should substitute the internal URLs with the external domain name. To make the substitution, you can use a JavaScript policy. This replacement works by extracting the response content, replacing the URL with a global search option, and then resetting the response content.

  1. In Apigee, add the JavaScript policy to the proxy. Click the icon next to the Policies section and select the JavaScript policy from the list, as shown in the following image. Enter the following values:

    • Name: JS-Replace-URL
    • Script Name: JS-Replace-URL.js

    Add JavaScript policy.

  2. Within the Resources section and the jsc subsection, select JS-Replace-URL.js. Making this selection shows the contents of the JavaScript file, as shown in the following image. Copy and paste the following JavaScript code:

    // Gets JSON response
    var responseData = response.content;
    // Get the Cloud Healthcare API path and proxy domain variables that are set in the common-config shared flow
    var hcaPath = context.getVariable("gcp.healthcareapi-path");
    var proxyDomain = context.getVariable("gcp.proxy-domain");
    // Build URLs and Paths
    var targetPath = "https://healthcare.googleapis.com/v1/" + hcaPath + "/fhir";
    var targetPathRegExp = new RegExp(targetPath, 'g');
    var proxyUrl = "https://" + proxyDomain + context.getVariable("proxy.basepath");
    
    // Replace HCA URL with API URL
    responseData = responseData.replace(targetPathRegExp, proxyUrl);
    // Set target response
    context.setVariable("response.content", responseData);
    

    Show JS-Replace-URL.js code.

  3. Expand the Proxy Endpoints > default > PostFlow section. Drag the JavaScript policy to the Response section, as shown in the following image.

    Drag JavaScript policy.

When the proxy calls the Cloud Healthcare API, it authenticates with service account credentials. To authenticate, set the authentication mechanism to use an access token. When the proxy is deployed, specify the service account you want to use.

  1. To use the service account credentials, expand the Target Endpoints > default > PreFlow section. Add an <Authentication> section to the HttpTargetConnection section of the XML file:

           </TargetEndpoint>
            ………
        <HTTPTargetConnection>
            <URL>https://healthcare.googleapis.com/v1/{gcp.healthcareapi-path}/fhir</URL>
            <Authentication>
                <GoogleAccessToken>
                    <Scopes>
                        <Scope>https://www.googleapis.com/auth/cloud-platform</Scope>
                    </Scopes>
                </GoogleAccessToken>
            </Authentication>
        </HTTPTargetConnection>
    </TargetEndpoint>
    
  2. Click Save to save the proxy.

  3. Click the Deploy drop-down, and then click Deploy {Version} next to the environment where you want to deploy the API proxy.

When you deploy the API proxy, the page prompts you to enter an optional service account. Enter the service account that you created in Before You Begin earlier in this document.

Setting the service account enables Apigee to connect to the Cloud Healthcare API using the service account identity. It also calls the Google authentication service to get a token.

For more information about using Google authentication, see Using Google authentication.

Deploying the proxy makes the proxy endpoint live. Once it's live, it's available at the URL that the Apigee instance was configured for.

Create an OAuth 2.0 API proxy

The FHIR API proxy that you created in a previous step is protected by an access token. Without this protection, the API is open to the public. One of the techniques you can use to protect an API is creating an OAuth 2.0 API proxy. In this section, you create a basic OAuth 2.0 API proxy using the client credentials grant type. You use the proxy to get an access token. You use the token to access the FHIR API.

  1. From the Apigee menu, under the Develop section, select API Proxies. Click Create New.
  2. Create a new API proxy with the following options:
    • No Target: Select
    • Name: oauth-api-v1
    • Base path: /oauth2
    • Security: Authorization: Passthrough (no authorization): Select
  3. Click Create to create the proxy.
  4. Click Edit Proxy to see the proxy's edit page.
  5. Add a new conditional flow for the API resource: /token, as shown in the following image.

    • Click the icon next to the Proxy Endpoints > Default section.
    • Enter the following values:
      • Flow Name: Get-Access-Token
      • Condition Type: Path and Verb
      • Path: /token
      • Verb: POST
  6. Click Add.

    Add new conditional flow.

Add an OAuth v2.0 policy to the proxy.

  1. Click the Develop tab.
  2. Click the icon next to the Policies section.
  3. Select OAuth v2.0 from the list. Click Add.
  4. Click the newly added policy and enter the following XML:

    <OAuthV2 continueOnError="false" enabled="true" name="OAuth-v20">
        <!-- This policy generates an OAuth 2.0 access token using the client_credentials grant type -->
        <Operation>GenerateAccessToken</Operation>
        <!-- This is in milliseconds, so expire in an hour -->
        <ExpiresIn>3600000</ExpiresIn>
        <SupportedGrantTypes>
            <GrantType>client_credentials</GrantType>
        </SupportedGrantTypes>
        <GrantType>request.queryparam.grant_type</GrantType>
        <GenerateResponse/>
    </OAuthV2>
    

Add the OAuth v2.0 policy to the /token flow in the API proxy, as shown in the following image.

  1. Expand the Proxy Endpoints > default section and click the Get-AccessToken flow.
  2. Drag the OAuth-v2.0 policy to the Request area of the flow.

    Update Request area.

  3. Click Save to save the proxy.

  4. Click the Deploy drop-down, and then click Deploy {Version} next to the environment where you want to deploy the API proxy.

  5. Deploying the proxy makes the proxy endpoint live and available. You can now call it at the URL that the Apigee instance was configured for.

Create an API product, developer profile, and developer application

In the previous section, you created an FHIR API. In this section, you package the proxy into an API product, then create a developer profile and a developer application to test that API.

As an API provider, you create API products to bundle your API proxies and make them available to application developers to consume.

  1. To create an API product, click Publish > Apigee > API Products, then click Create, as shown in the following image.
  2. Enter the following values:

    • Name: FHIR R4 API
    • Display Name: FHIR R4 API
    • Access: Public
    • Environment: Select the environment that you deployed the shared flows and proxies to.
    • Automatically approve access requests: Select
    • Operations: Click the Add an Operation button and fill in the following fields:
      • API Proxy: fhir-r4-api-v1 proxy
      • Operation: /**
      • Methods: GET, POST, PUT, DELETE, OPTIONS
  3. Click Save.

    Update product details.

Apigee lets you look at both the exposing and consuming side of the API. This tutorial focuses on building the API and securely exposing the FHIR data. Creating a developer profile lets you test the consuming side of the API.

This part of the tutorial shows you how to create an app that consumes the API.

To create a developer profile, from the Apigee menu, complete the following steps:

  1. Click Publish > Developers.
  2. Click Developer.
  3. Enter the following values (or use your own):
    • First Name: App
    • Last Name: Developer
    • Username: appdeveloper
    • Email: Enter an email address where you can receive email.

A developer might be working on several different applications that each need their own API key. The API key represents the combination of a developer's application and the API product that the developer's application needs to access.

To create a developer app, from the Apigee menu, build an application profile:

  1. Click Publish Apps.
  2. Click App.
  3. Enter the following values, as shown in the following image:
    • Name: FHIR R4 App
    • Display Name: FHIR R4 App
    • Developer:
  4. Click Add product.
    • Select the API product that you created (FHIR R4 API).
    • Set the status to Approved.
  5. Click Create.

    Create a new app.

Test the API call

To test the API call, use the cURL tool. Run cURL from the command line or from Cloud Shell:

  1. From the Apigee menu, click Publish > Apps. Click the app FHIR R4 App that was created previously.
  2. From the Credentials section, click the Show link for both the key and the secret. The credentials display, as shown in the following image.

    Credentials information.

  3. Open a base64 encoding tool. Copy the key and secret into the following format and base64 encode the string.

    • key:secret
    • Result Example: a2V5MjN4ZGRzcnNlcjM0c2Q6c2VjcmV0M2Y0NHJ3NTNzZGY=
  4. Use cURL to call the OAuth 2.0 proxy to retrieve the access token. The access token is in the JSON response of the API call.

    curl -X POST https://{api-domain-name}/oauth2/token?grant_type=client_credentials -H "Authorization: Basic {base64string}"
    

    The output is similar to the following:

    {
      "refresh_token_expires_in" : "0",
      "api_product_list" : "[FHIR R4 API]",
      "api_product_list_json" : [ "FHIR R4 API" ],
      "organization_name" : "apigee-org-name",
      "developer.email" : "appdeveloper@google.com",
      "token_type" : "BearerToken",
      "issued_at" : "1623419965745",
      "client_id" : "CUH07Q1EAmd1hqf94a13PF1oGBG3wtTi",
      "access_token" : "1n3Bh7yIWxTRYGord4xAOmqiZsHf",
      "application_name" : "a619aa68-f34f-4f1c-9511-c6abda60464f",
      "scope" : "",
      "expires_in" : "3599",
      "refresh_count" : "0",
      "status" : "approved"
    }
    
  5. Copy the data in the access_token field that appears in the preceding output example. You use it in the next step.

  6. Call the FHIR API to retrieve a list of patients:

    • Use the access_token value from the OAuth 2.0 call response in the Authorization header.
    • Add the /Patient FHIR resource at the end of the URL.
    • The response is a list of all patients:
    curl https://{api-domain-name}/v1/fhir/r4/Patient -H "Authorization: Bearer {access_token}"
    
    {
      "entry": [
        {
          "fullUrl": "https://{api-domain-name}/v1/fhir/r4/Patient/619e4e4b-2a02-478c-9ef4-cc2c40e84189",
          "resource": {
            "address": [
              {
    …………..
    
        }
      ]
    }
    
  7. Call the FHIR API to retrieve the information for one patient:

    • From the previous API call, select a patient ID.
    • Append the patient ID to the end of the /Patient resource.
    • The response returns the data for the selected patient:
    curl https://{api-domain-name}/v1/fhir/r4/Patient/(id) -H "Authorization: Bearer {access_token}"
    
    {
      "entry": [
        {
          "fullUrl": "https://{api-domain-name}/v1/fhir/r4/Patient/619e4e4b-2a02-478c-9ef4-cc2c40e84189",
          "resource": {
            "address": [
              {
    …………..
    
        }
      ]
    }
    

Try calling other FHIR resources. There are over 100 FHIR resources available—for example: /Practitioner, /Encounter, /ExplanationOfBenefit, /Coverage.

    curl https://{api-domain-name}/v1/fhir/r4/Practitioner -H "Authorization: Bearer {access_token}"

    curl https://{api-domain-name}/v1/fhir/r4/Encounter -H "Authorization: Bearer {access_token}"

This tutorial shows you how to connect to the Google Cloud Healthcare API with Apigee.

There are other things you can do with Apigee, like impose quotas and rate limiting, view analytics, publish to the developer portal, and customize the developer portal.

Clean up

To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, either delete the project that contains the resources, or keep the project and delete the individual resources.

There is no charge for the Apigee trial. The Apigee trial expires and deletes on its own after 60 days. To avoid incurring charges to your Google Cloud account for the resources used in this tutorial, do the following:

Delete the FHIR store

To delete the FHIR datastore, see Deleting a FHIR store.

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. If the project that you plan to delete is attached to an organization, expand the Organization list in the Name column.
  3. In the project list, select the project that you want to delete, and then click Delete.
  4. In the dialog, type the project ID, and then click Shut down to delete the project.

What's next