記事
· 9 hr 前 10m read

Googleフォームとの統合

Googleフォームは、データ収集、アンケートやクイズへの回答を行うための市場で最も人気のソリューションです。そのため、システムを拡張または開発することなく、患者データや回答を実用的な方法で収集するのに理想的な手段と言えます。本記事では、Google Cloudにアカウントを作成し、Google Forms APIを利用するアプリケーションを登録します。また、APIを利用するためのサービスユーザーを生成して、最後にEmbedded PythonとIRISを用いて新しいフォームを作成し、入力されたデータを自動的に収集する方法ついて詳しく説明します。

Google Cloudアカウントの作成

Google Cloudアカウントをお持ちでない場合、これらの手順に従ってください。すでにお持ちの場合は、次のセクションに進みます。
Google Cloud Platform(GCP)アカウントを作成するには、最初にGoogleアカウントを作成する必要があります。 次に、Google Cloudコンソールにサインインし、無料枠を利用開始するか、課金アカウントを作成できます。 ステップバイステップガイドは次のとおりです。

1.    Google Cloudコンソールに移動する。cloud.google.comにアクセスします。
2.    Googleアカウントにサインインする。Googleアカウントをお持ちでない場合は、作成する必要があります。
3.    利用規約に同意する。Google Cloud利用規約を確認して同意します。
4.    無料で開始するか、課金アカウントを作成する。
a.    無料枠:無料枠では無料でGoogle Cloudの使用を開始できます。
b.    課金アカウント:より多くのリソースや高度な機能が必要な場合は、課金アカウントを作成する必要があります。
5.    課金アカウントを作成する(必要な場合):課金アカウントを作成する場合、支払い情報の確認と組織情報の入力が必要です。
6.    開始する:アカウントが設定されたら、Google Cloudコンソールにアクセスしてサービスの使用を開始できます。   

Google Cloudプロジェクトの作成
 

プログラムでGoogle APIやSDKを使用するには、プロジェクトを作成する必要があります。
以下のリンク先に移動して、リンク先の手順に従ってください:https://developers.google.com/workspace/guides/create-project

 

Google Cloudサービスアカウントの作成

アプリケーションがGoogle Forms APIを利用するには、サービスアカウント(アプリの認証情報)を作成する必要があります。

1.    https://console.cloud.google.com/projectselector2/iam-admin/serviceaccountsにアクセスして、前のセクションで選択したプロジェクトを選びます。
2.   「+ Create service account(+ サービスアカウントの作成)」ボタンをクリックして必要なフィールドに入力し、「Create(作成)」ボタンを押して先に進みます。
3.    「Owner(所有者)」ロールを選択して、「Continue(続行)」をクリックします。
4.    後で使うために認証情報JSONファイルを保存します。
5.    「Done(完了)」ボタンをクリックします。
6.    3 点アイコンをクリックして、「Manage keys(キーを管理)」を選択します。
 
7.    「Add key(キーを追加)」 > 「Create new key(新規キーを追加)」ボタンをクリックします
8.    JSONを選択して、「Create(作成)」をクリックします。
 
9.    認証情報がダウンロードページに保存されます。後で使用するため、このファイルを保存してください。


Google Forms APIとGoogle Drive APIの有効化

プロジェクトでGoogleフォームとGoogleドライブを使用する(ドライブにGoogleフォームの定義が保存されるため)には、アクセスを有効化する必要があります。
1.    https://console.cloud.google.com/apis/dashboardに移動します
2.    「+ Enable APIs and services(+ APIとサービスを有効化)」ボタンをクリックします
3.    上部の「Search for APIs & Services(API&サービスを検索)」フィールドでGoogle Drive APIを検索し、まだ有効になっていない場合はAPIを有効化します。
4.    ステップ3を繰り返し、「Search for APIs & Services(API&サービスを検索)」フィールドで Google Forms APIを検索し、まだ有効になっていない場合はAPIを有効化します。


health-gformsプロジェクトの取得と実行

Googleフォームを作成して、データを収集するサンプルのアプリケーション(health-gforms、https://openexchange.intersystems.com/package/health-gforms)を作成しました。


1.    任意のローカルディレクトリにリポジトリをクローン/git pull します
$ git clone https://github.com/yurimarx/health-gforms/health-gforms.git
2.    このディレクトリでターミナルを開いて実行します。
$ docker-compose build
$ docker-compose up -d

 

Postman経由でのhealth-gforms APIの利用


1.    Postmanアプリケーションまだお持ちでない場合は、ダウンロード(https://www.postman.com/downloads/)してインストールします。
2.    https://github.com/yurimarx/health-gforms/raw/refs/heads/master/health-g...からpostmanコレクションをダウンロードします
3.    このコレクションをPostmanにインポートします。
 
4.   「1. Post credentials(認証情報を送信)」をクリックして DockerインスタンスにGoogle Cloudサービスアカウント認証情報をアップロードします。
 
5.   「2. Post form definition(フォーム定義を送信)」をクリックして dockerインスタンスにフォーム定義を保存します(rootプロジェクトフォルダーにあるファイル、formpatient.jsonを使用します)。
 
6.    「3. Create form from the definision(定義からフォームを作成)」をクリックして Google Cloud上に新規Googleフォームを作成し、新しい患者についての情報を収集します。
 
7.    値をformIdにコピーします。
 
8.    ブラウザでGoogleフォームを開きます(formIdの値に注意してください。https://docs.google.com/forms/d/1DtqV5edXVOjM-FAntPffRHqfVjMjOIJuiq5VXBc...のパスで使用しました)。
 
9.    エンドユーザーとしてGoogleフォームを入力するには、「participant link(参加リンク)」ボタンにアクセスし、新しいブラウザタプに貼り付けます。
 
10.    エンドユーザーとしてフォームに入力します。
 
11.    フォームの回答を投稿します。
12.   「4. Get form content from template(テンプレートからフォームコンテンツを取得)」をクリックして formIdの値をステップ7で提供したformIdに変更します。
 
13.   「Send(送信)」ボタンをクリックして、fhir jsonコンテンツがFHIRサーバーに送信されるのを確認します。

 

制作の裏側

Googleフォームへのフォーム作成

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. フォームとドライブのAPI用に、認証情報JSONファイル内のサービスアカウントのデータを使用して認証情報を作成します。

2. この認証情報を使用して、form_serviceをビルドします。

3. form_serviceは、ヘッダーのみを含むGoogleフォームを作成するために使用されます。

4. form_serviceはformpatient.jsonを読み取り、フォームの項目(フィールドや質問)を作成します。 このファイルのコンテンツは次のとおりです。

{
    "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. これで新しいフォームが作成されました。

Googleフォームからユーザーの回答データを収集します。

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. credentials.jsonで定義されたサービスアカウントを使用して、Googleフォームを読み取る権限を持つ認証情報オブジェクトが作成されます。

2. form_serviceは認証情報から作成されます。

3. form_serviceは、formIdからすべての回答を取得するために使用されます。

@Yuri Marxさんが書いた元の記事へ
ディスカッション (0)0
続けるにはログインするか新規登録を行ってください