Python で RPC リクエストを送信する

アプリケーションは、gRPC と Python を使用して Universal Ledger API とやり取りできます。このアプローチでは、サービスのプロトコル バッファ定義からコンパイルされた Python クライアント ライブラリを生成して使用します。

このチュートリアルでは、Universal Ledger API のクライアントを実装するデベロッパー向けに、適切な開発環境の設定、必要なライブラリの生成、Python を使用した gRPC 呼び出しの方法について説明します。

始める前に

このチュートリアルを完了するには、次のものが必要です。

  • Universal Ledger API が有効になっている Google Cloud プロジェクト。

  • universalledger.googleapis.com/endpointViewer などの IAM ロール。これにより、少なくとも Universal Ledger エンドポイントを表示できます。

  • ユーザー アカウントのローカル認証情報。次のコマンドを実行して、これらの認証情報を構成します。

    gcloud auth application-default login

これらの手順の詳細については、 限定公開プレビュー版のオンボーディング ガイドをご覧ください。

環境の設定

このチュートリアルの手順は、Ubuntu 25.04 を実行する環境向けに記述されています。この環境には、デフォルトで Python 3.13 が含まれています。別のオペレーティング システムを使用している場合は、コマンドの変更が必要になることがあります。

開発環境を設定するには、次の手順を行います。これらの手順では、必要なコマンドライン ツールをインストールします。これには、gRPC バインディングのビルドに使用される grpcio-tools をインストールするために pipx を使用することが含まれます。このプロジェクトの Python 依存関係を分離するには、Python 仮想環境を作成して有効にし、pip を使用して必要な Python ライブラリをインストールします。

  1. 次のコマンドを使用して、基本の依存関係をインストールします。

    sudo apt update
    sudo apt install git pipx python3.13-venv
  2. pipx を使用して gRPC ツール アプリケーションをインストールし、そのバイナリ ディレクトリが PATH に追加されていることを確認します。

    pipx install grpcio-tools
    pipx ensurepath

    ターミナルを閉じて再度開き、pipx の有効化を完了します。

  3. このチュートリアルのファイルを保持する親ディレクトリを作成します。

    mkdir gcul_tutorial
    cd gcul_tutorial

    特に指定がない限り、残りのコマンドはこの新しいディレクトリ内で実行する必要があります。

  4. Python 仮想環境を作成し、残りのライブラリをインストールします。

    python3 -m venv example_client
    cd example_client
    source ./bin/activate
    pip3 install google-auth googleapis-common-protos grpcio requests
    cd ..

    これらのライブラリは次のとおりです。

    • google-auth: 認証の処理用。 Google Cloud
    • googleapis-common-protos: Google API 全体で使用される共通のプロトコル バッファ メッセージ。
    • grpcio: Python 用の gRPC ライブラリ。
    • requests: HTTP リクエストを送信するために、一部の依存関係で必要になります。

プロトコル バッファ ライブラリを生成する

gRPC を使用して Universal Ledger API とやり取りするには、Python アプリケーションに サービスの プロトコル バッファ.proto)定義からコンパイルされたクライアント ライブラリが必要です。これらの定義では、API のサービス、メソッド、メッセージ タイプを指定します。

このセクションでは、googleapis リポジトリからこれらの .proto ファイルをダウンロードし、インストールした grpcio-tools を使用して必要な Python ソースコードを生成する方法について説明します。

  1. Google API のプロトコル バッファ定義が公開されている googleapis GitHub リポジトリのクローンを作成します。

    git clone https://github.com/googleapis/googleapis.git
  2. Universal Ledger API のプロトコル バッファ定義と gRPC バインディングをビルドします。

    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        --grpc_python_out=example_client \
        google/cloud/universalledger/v1/universalledger.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/query.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/accounts.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/common.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/transactions.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/types.proto
    python-grpc-tools-protoc --proto_path=googleapis/ \
        --python_out=example_client \
        --pyi_out=example_client \
        google/cloud/universalledger/v1/status_event.proto

    これにより、example_client/google/cloud/universalledger/v1 ディレクトリに複数のファイルが作成されます。

    accounts_pb2.py
    accounts_pb2.pyi
    common_pb2.py
    common_pb2.pyi
    query_pb2.py
    query_pb2.pyi
    status_event_pb2.py
    status_event_pb2.pyi
    transactions_pb2.py
    transactions_pb2.pyi
    types_pb2.py
    types_pb2.pyi
    universalledger_pb2.py
    universalledger_pb2.pyi
    universalledger_pb2_grpc.py
    

Universal Ledger API を呼び出す

最後に、生成されたライブラリを使用して Universal Ledger API を呼び出す Python スクリプトを作成します。次のコードを example_client/endpoints.py として保存します。

コードで、次のプレースホルダ値を置き換えます。

  • PROJECT_ID: 実際の Google Cloud プロジェクト ID(例: my-project)。
  • REGION: Universal Ledger エンドポイントが配置されている Google Cloud リージョン(例: us-east5)。
"""Example calling the Universal Ledger API."""

import sys

import google.auth
import google.auth.transport.grpc
import google.auth.transport.requests
from google.cloud.universalledger.v1 import universalledger_pb2
from google.cloud.universalledger.v1 import universalledger_pb2_grpc
import grpc

API_ENDPOINT = "universalledger.googleapis.com"
PROJECT = "PROJECT_ID"
REGION = "REGION"
SCOPES = ["https://www.googleapis.com/auth/cloud-platform"]


def main() -> str | None:
  # Get the application default credentials.
  credentials, _ = google.auth.default(scopes=SCOPES)

  # Get an HTTP request function to refresh credentials.
  refresh_request = google.auth.transport.requests.Request()

  # Create a secure channel to the API endpoint.
  with google.auth.transport.grpc.secure_authorized_channel(
      credentials, refresh_request, API_ENDPOINT
  ) as channel:
    # Create the client stub using the generated code.
    stub = universalledger_pb2_grpc.UniversalLedgerStub(channel)

    # Parent location for GCUL network endpoints.
    parent = f"projects/{PROJECT}/locations/{REGION}"

    # Build the request message.
    request = universalledger_pb2.ListEndpointsRequest(parent=parent)

    # Make the gRPC call.
    try:
      metadata = [("x-goog-request-params", f"parent={parent}")]
      response = stub.ListEndpoints(request, metadata=metadata)
    except grpc.RpcError as exc:
      return f"{exc.code().name}: {exc.details()}"

    if not response.endpoints:
      return f"No endpoints found under: {parent}"

    print("Found the following endpoints:")
    for endpoint in response.endpoints:
      print("-", endpoint.name)


if __name__ == "__main__":
  sys.exit(main())

スクリプトを実行するには、example_client ディレクトリに移動します。 仮想環境は、設定手順で有効にした状態のままにする必要があります。

  1. スクリプト ディレクトリに移動します。

    cd example_client
    

    シェル プロンプトで、仮想環境が有効になっていることを確認します(たとえば、先頭に (example_client) が付いています)。

  2. Python スクリプトを実行します。

    python3 endpoints.py
    

次のような出力が表示されます。

Found the following endpoints:
- projects/my-project/locations/us-east5/endpoint/gcul-pilot-testing
- projects/my-project/locations/us-east5/endpoint/gcul-user-testing

次のステップ