Article
· Jul 6, 2023 6m read

Facilitating Document Export: Share Text and Tabular Data to Google Docs and Sheets

Idea sourced from InterSystems Ideas Portal

Previous Posts:

Using AI to Simplify Clinical Documents Storage, Retrieval, and Search

Doctor-Patient Conversations: AI-Powered Transcription and Summarization

Introduction

The healthcare industry is continuously evolving, and the need for efficient document management and patient data management is more critical than ever. In this article, we will focus on the specific aspects of integrating Google Docs and Google Sheets with FHIR data in the context of healthcare data interoperability.

Google Docs Integration for Clinical Documents

Integrating Google Docs with FHIR data allows healthcare providers to create, edit, and store medical notes directly within a patient’s records. This seamless integration enables real-time collaboration between healthcare professionals, ensuring that patient information is up-to-date and easily accessible. This can help them leverage the extensive features that Google Docs provide like Extensions, Charts, Variables, and Document AI solutions suite; healthcare providers can automate and improve operational efficiency.

Google Sheets Integration for Patient Data Management

Google Sheets can be utilized for managing and analyzing patient data, such as lab results, medications, and appointments. By integrating Google Sheets with FHIR data, healthcare providers can create, edit, and share patient data in a secure and collaborative environment. This can help them leverage the extensive features that Google Sheets provide like Extensions, Charts, Macros, and Apps script solutions suite; healthcare providers can automate and improve operational efficiency.

Technical Implementation

OAuth 2.0 to Access Google APIs

Steps to generate gClient ID - https://github.com/ikram-shah/iris-fhir-transcribe-summarize-export/blob/master/README.md#configure-google-oauth-client-id

Steps to generate a token and save it in browser window session - When the frontend application is loaded, two functions are called. Refer to iris-fhir-transcribe-summarize-export/src/vue/src/components/TopBar.vue

initGoogleOAuth(gClientId) {
      this.gClient = window.google.accounts.oauth2.initTokenClient({
        client_id: gClientId,
        scope:
          "https://www.googleapis.com/auth/documents https://www.googleapis.com/auth/spreadsheets",
        callback: this.handleOauthToken,
      });
      window.google.accounts.id.initialize({
        client_id: gClientId,
        callback: this.handleCredentialResponse,
      });
    }, 

//called from initGoogleOAuth
async handleCredentialResponse(response) {
      try {
        this.gClient.requestAccessToken();
        console.log(response);
      } catch (error) {
        console.error(error);
      }
    }, 

//called from initGoogleOAuth
async handleOauthToken(response) {
      this.oAuth = response["access_token"];
      localStorage.setItem("oAuth", this.oAuth);
    },

 

renderGoogleLoginButton() {
      window.google.accounts.id.renderButton(this.$refs.googleLoginBtn, {
        text: "Login",
        size: "large",
        theme: "filled_blue", // options: filled_black | outline | filled_blue
      });
    },

And in the HTML code,

<button ref="googleLoginBtn"></button>

Google Docs Export Core Function

Google Docs API requires two calls, one to create and another to update the doc with the template with content to be inserted. Below is the code snippet for both of these calls. The insertText content is key here to create docs of all styles. Here we have only used plain text to insert, but any text formatting option seen in Google Docs UI can be replicated and inserted into docs via the API calls. Multiple templates based on the use-case of the export can be created and used in the calls appropriately.

Note that only the user who authorized the doc creation via Oauth2 has access to create this doc. This ensures least-privilege access and the creator is free to share the doc with others when needed.

def CreateGoogleDoc(title, body, token):
    url = 'https://docs.googleapis.com/v1/documents'     
    base64_bytes = body.encode('utf-8')
    message_bytes = base64.b64decode(base64_bytes)     

    # Set the desired document content
    document_content = {
        'title': title,
    }     # Convert the document content to JSON
    document_json = json.dumps(document_content)     

    # Send the API request to create the document
    response = requests.post(
        url,
        headers={'Authorization': f'Bearer {token}',
                 'Content-Type': 'application/json'},
        data=document_json
    )     # Set the desired document content
    document_content = {
        "requests": [
            {
                "insertText": {
                    "text": message_bytes.decode('utf-8'),
                    "location": {
                        "index": 1,
                    },
                },
            },
        ],
    }     # Convert the document content to JSON
    document_json = json.dumps(document_content)     

    # Send the API request to create the document
    response = requests.post(
        "https://docs.googleapis.com/v1/documents/"+document_id+":batchUpdate",
        headers={'Authorization': f'Bearer {token}',
                 'Content-Type': 'application/json'},
        data=document_json
    )     return json.dumps(resp)

 

 

Google Sheets Export Core Function

Similar to Docs, Sheets API also requires two calls, one to create and another to update the sheet with the rows to be inserted. Below is the code snippet for both of these calls. The range and dimension fields are key to place the data in appropriate cells in sheets.

def CreateGoogleSheet(title, rowsJson, token):
    body = json.dumps({
        "properties": {
            "title": title
        }
    })     rows = json.loads(rowsJson)
    
    # Send the API request to create the sheet
    response = requests.post(
        "https://sheets.googleapis.com/v4/spreadsheets",
        headers={'Authorization': f'Bearer {token}',
                 'Content-Type': 'application/json'},
        data=body
    )     body = json.dumps({
        "range": "Sheet1!A1",
        "majorDimension": "ROWS",
        "values": rows
    })     

    # Send the API request to create rows in the sheet
    response = requests.put(
        "https://sheets.googleapis.com/v4/spreadsheets/" + resp["googleSheetId"] +
        "/values/Sheet1!A1?valueInputOption=USER_ENTERED",
        headers={'Authorization': f'Bearer {token}',
                 'Content-Type': 'application/json'},
        data=body
    )
    return json.dumps(resp)

Vote for our app in the Grand Prix contest if you find it promising!

If you can think of any potential applications using this technology, please feel free to share them in the discussion thread.

Discussion (0)1
Log in or sign up to continue