Article
· May 29 8m read

Integrate with Google Forms

Google Forms is the most popular solution on the market for collecting data, answering questionnaires and quizzes. So, it is the ideal solution for collecting patient data and responses in a practical way, without the need to expand or develop systems. In this article, I will detail how to create an account on Google Cloud, register the application that will consume the Google Forms API, generate the service user necessary to consume the API and finally perform actions to create new forms and collect data filled in them in an automated way in embedded Python and IRIS.

Create your Google Cloud account

If you don’t have Google Cloud account, follow these steps, otherwise go to the next section.
To create a Google Cloud Platform (GCP) account, you first need a Google account. Then, you can sign in to the Google Cloud console and start using the free tier or create a paid account. Here's a step-by-step guide:

1.    Go to the Google Cloud console: Visit cloud.google.com.
2.    Sign in with your Google account: If you don't have one, you'll need to create one.
3.    Accept the terms and conditions: Review and accept the Google Cloud terms and conditions.
4.    Start Free or Create a Billing Account:
a.    Free Tier: You can start using Google Cloud for free with the free tier.
b.    Paid Account: If you need more resources or advanced features, you'll need to create a billing account.
5.    Create a Billing Account (if needed): If you choose to create a paid account, you'll need to set up a billing account, which requires providing payment verification details and information about your organization.
6.    Get Started: Once your account is set up, you can access the Google Cloud console and start using the services.   

Create a Google Cloud project
 

It is mandatory to create a project to use Google APIs and SDKs into your programs.
Go to this link and follow the steps: https://developers.google.com/workspace/guides/create-project

 

Create a Google Cloud Service Account

It is required create a service account (credentials for applications) to your application consume the Google Forms API.

1.    Go to https://console.cloud.google.com/projectselector2/iam-admin/serviceaccounts , select the project that you selected in the previous section.
2.    Click the button + Create service account, fill the required fields and click the button Create and continue.
3.    Select the role Owner and click the Continue button.
4.    Save your Credentials JSON file to use later.
5.    Click the button Done.
6.    Click the button 3 dots and select Manage keys:
 
7.    Click the button Add key > Create new key
8.    Select JSON and click Create:
 
9.    The credentials are saved into your downloads page, SAVE THIS FILE BECAUSE I WILL USE IT LATER.


Enable Google Forms and Google Drive APIs

To your project consume the Google Forms and Google Drive (because Drive store the Google Forms definitions), you must enable the access:
1.    Go to https://console.cloud.google.com/apis/dashboard
2.    Click the button + Enable APIs and services
3.    Search for Google Drive API on the top field Search for APIs & Services, select Google Drive API and enable the API, if not enabled yet.
4.    Repeat the step 3 and Search for Google Forms API on the top field Search for APIs & Services, select Google Forms API and enable the API, if not enabled yet.


Get and run the health-gforms project

I created a sample application (health-gforms at https://openexchange.intersystems.com/package/health-gforms) that create a Google Form and collect data from it.


1.    Clone/git pull the repo into any local directory
$ git clone https://github.com/yurimarx/health-gforms/health-gforms.git
2.    Open the terminal in this directory and run:
$ docker-compose build
$ docker-compose up -d

 

Using the health-gforms API via Postman


1.    Download (https://www.postman.com/downloads/) and install the Postman application, if you don’t have this application yet.
2.    Download the postman collection from https://github.com/yurimarx/health-gforms/raw/refs/heads/master/health-g...
3.    Import this collection into your Postman:
 
4.    Click the 1. Post credentials to upload the google cloud service account credentials into your docker instance:
 
5.    Click the 2. Post form definition, to save the form definition (use a file from our root project folder, formpatient.json) into our docker instance:
 
6.    Click 3. Create form from file definition, to create a new google form on Google cloud and to collect data about a new patient:
 
7.    Copy the value into formId:
 
8.    Open the Google forms using your browser (pay attention for formId value, I used it into the path: https://docs.google.com/forms/d/1DtqV5edXVOjM-FAntPffRHqfVjMjOIJuiq5VXBc...
 
9.    To fill the Google Forms as end user, go to the button participant link   and past in a new browser tab:
 
10.    Fill the form as end user:
 
11.    Post the form answers.
12.    Click the 4. Get form content from template and change the value formId with the formId provided in the step 7:
 
13.    Click the send button and see the fhir json content to send to your FHIR server:

 

Behind the Scenes

Creating a Form into Google Forms:

ClassMethod CreateFormFromFile(formtitle As %String, filepath As %String) [ Language = python ]
{
    
    import httplib2
    import json
    from oauth2client.service_account import ServiceAccountCredentials
    from googleapiclient.discovery import build
    from mako.template import Template

    
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        "/opt/irisapp/credentials.json",
        scopes=["https://www.googleapis.com/auth/forms.body", 
                "https://www.googleapis.com/auth/forms", 
                "https://www.googleapis.com/auth/drive", 
                "https://www.googleapis.com/auth/drive.file"],
    )

    http = httplib2.Http()
    http = credentials.authorize(http)

    form_service = build("forms", "v1", http=http)

    new_form_template = Template('{"info": {"title": "${title}"}}')
    new_form_str = new_form_template.render(title=formtitle)
    NEW_FORM = json.loads(new_form_str)

    # Create the form
    try:
        result = form_service.forms().create(body=NEW_FORM).execute()
        formid = result["formId"]
        print(f'Form created: {result}')

        with open(filepath) as file:
            itemsjson = json.loads(file.read())
            # Adds form items
            items = (
                form_service.forms()
                .batchUpdate(formId=formid, body=itemsjson)
                .execute()
            )

        permission2 = {
            'type': 'anyone',
            'role': 'writer',
        }

        drive_service = build('drive', 'v3', credentials=credentials)

        drive_service.permissions().create(fileId=formid, body=permission2).execute()

        return formid
    except Exception as e:
        print(f'Error creating form: {e}')
}

1. We create the credentials using the service account data inside a credentials json file for form and drive apis.

2. We use this credentials to build a form_service.

3. The form_service is used to create the Google Form with header only.

4. The form_service reads the formpatient.json to create the forms itens (fields or questions). See this file content:

{
    "requests": [
        {
            "createItem": {
                "item": {
                    "title": "Given Name",
                    "questionItem": {
                        "question": {
                            "required": true,
                            "textQuestion": {}
                        }
                    }
                },
                "location": {"index": 0}
            }
        },
        {
            "createItem": {
                "item": {
                    "title": "Family Name",
                    "questionItem": {
                        "question": {
                            "required": true,
                            "textQuestion": {}
                        }
                    }
                },
                "location": {"index": 1}
            }
        },
        {
            "createItem": {
                "item": {
                    "title": "Gender",
                    "questionItem": {
                        "question": {
                            "required": true,
                            "choiceQuestion": {
                                "type": "RADIO",
                                "options": [
                                    {
                                        "value": "male"
                                    },
                                    {
                                        "value": "female"
                                    }
                                ]
                            }
                        }
                    }
                },
                "location": {"index": 2}
            }
        },
        {
            "createItem": {
                "item": {
                    "title": "Birth Date",
                    "questionItem": {
                        "question": {
                            "required": true,
                            "dateQuestion": {
                                "includeYear": true
                            }
                        }
                    }
                },
                "location": {"index": 3}
            }
        },
        {
            "createItem": {
                "item": {
                    "title": "Phone",
                    "questionItem": {
                        "question": {
                            "required": true,
                            "textQuestion": {}
                        }
                    }
                },
                "location": {"index": 4}
            }
        }
    ]   
}

5. Now we have a new form.

Collect user data responses from a Google Form:

ClassMethod GetResponsesFromFormId(formid As %String) [ Language = python ]
{
    import httplib2
    from oauth2client.service_account import ServiceAccountCredentials
    from googleapiclient.discovery import build

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        "/opt/irisapp/credentials.json",
        scopes="https://www.googleapis.com/auth/forms.responses.readonly",
    )

    # Create an httplib2.Http object to handle our HTTP requests and authorize
    # it with the Credentials.
    http = httplib2.Http()
    http = credentials.authorize(http)

    form_service = build("forms", "v1", http=http)

    # Prints the responses of your specified form:
    result = form_service.forms().responses().list(formId=formid).execute()
    return result
}

1. A credential object is created using the service account defined into credentials.json with authorization to read google forms.

2. A form_service is created from the credentials.

3. The form_service is used to get all responses from a formId.

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

Hi Yuri,

Your video is available on InterSystems Developers YouTube:

⏯️Collect data with Google Forms and send it to FHIR Server

https://www.youtube.com/embed/xn9C1V3zd-I?si=H_7nsxIXEnUUuzfY
[This is an embedded link, but you cannot view embedded content directly on the site because you have declined the cookies necessary to access it. To view embedded content, you would need to accept all cookies in your Cookies Settings]