애플리케이션은 gRPC 및 Python을 사용하여 범용 원장 API와 상호작용할 수 있습니다. 이 접근 방식에서는 서비스의 프로토콜 버퍼 정의에서 컴파일된 Python 클라이언트 라이브러리를 생성하고 사용합니다.
이 튜토리얼에서는 Universal Ledger API용 클라이언트를 구현하려는 개발자에게 적합한 개발 환경을 설정하고, 필요한 라이브러리를 생성하고, Python을 사용하여 gRPC 호출을 하는 방법을 보여줍니다.
시작하기 전에
이 튜토리얼을 완료하려면 다음이 필요합니다.
Universal Ledger API가 사용 설정된 Google Cloud 프로젝트
universalledger.googleapis.com/endpointViewer와 같은 IAM 역할로, 최소한 범용 원장 엔드포인트를 볼 수 있습니다.사용자 계정의 로컬 인증 사용자 인증 정보입니다. 다음 명령어를 실행하여 이러한 사용자 인증 정보를 구성합니다.
gcloud auth application-default login
이 단계에 대해 자세히 알아보려면 비공개 미리보기 온보딩 가이드를 참고하세요.
환경 설정
이 튜토리얼의 안내는 Ubuntu 25.04를 실행하는 환경을 대상으로 작성되었으며, 여기에는 기본적으로 Python 3.13이 포함되어 있습니다. 다른 운영체제를 사용하는 경우 명령어를 수정해야 할 수 있습니다.
개발 환경을 설정하려면 다음 단계를 완료하세요. 이 단계에서는 필요한 명령줄 도구를 설치하는 방법을 안내합니다. 여기에는 pipx를 사용하여 gRPC 바인딩을 빌드하는 데 사용되는 grpcio-tools를 설치하는 것이 포함됩니다. 이 프로젝트의 Python 종속 항목을 격리하려면 Python 가상 환경을 만들고 활성화한 다음 pip를 사용하여 필요한 Python 라이브러리를 설치합니다.
다음 명령어를 사용하여 기본 종속 항목을 설치합니다.
sudo apt updatesudo apt install git pipx python3.13-venvpipx를 사용하여 gRPC 도구 애플리케이션을 설치하고 바이너리 디렉터리가PATH에 추가되었는지 확인합니다.pipx install grpcio-toolspipx ensurepath터미널을 닫았다가 다시 열어
pipx활성화를 완료합니다.이 튜토리얼의 파일을 저장할 상위 디렉터리를 만듭니다.
mkdir gcul_tutorialcd gcul_tutorial달리 지정하지 않는 한 나머지 명령어는 이 새 디렉터리 내에서 실행해야 합니다.
Python 가상 환경을 만들고 나머지 라이브러리를 설치합니다.
python3 -m venv example_clientcd example_clientsource ./bin/activatepip3 install google-auth googleapis-common-protos grpcio requestscd ..이러한 라이브러리는 다음과 같습니다.
google-auth: Google Cloud 인증을 처리합니다.googleapis-common-protos: Google API 전반에서 사용되는 공통 프로토콜 버퍼 메시지입니다.grpcio: Python용 gRPC 라이브러리입니다.requests: 일부 종속 항목이 HTTP 요청을 전송하는 데 필요합니다.
프로토콜 버퍼 라이브러리 생성
gRPC를 사용하여 범용 원장 API와 상호작용하려면 서비스의 프로토콜 버퍼(.proto) 정의에서 컴파일된 클라이언트 라이브러리가 Python 애플리케이션에 필요합니다. 이러한 정의는 API의 서비스, 메서드, 메시지 유형을 지정합니다.
이 섹션에서는 googleapis 저장소에서 이러한 .proto 파일을 다운로드하고 설치된 grpcio-tools를 사용하여 필요한 Python 소스 코드를 생성하는 방법을 보여줍니다.
Google API의 프로토콜 버퍼 정의가 게시된 googleapis GitHub 저장소를 클론합니다.
git clone https://github.com/googleapis/googleapis.git범용 원장 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.protopython-grpc-tools-protoc --proto_path=googleapis/ \ --python_out=example_client \ --pyi_out=example_client \ google/cloud/universalledger/v1/query.protopython-grpc-tools-protoc --proto_path=googleapis/ \ --python_out=example_client \ --pyi_out=example_client \ google/cloud/universalledger/v1/accounts.protopython-grpc-tools-protoc --proto_path=googleapis/ \ --python_out=example_client \ --pyi_out=example_client \ google/cloud/universalledger/v1/common.protopython-grpc-tools-protoc --proto_path=googleapis/ \ --python_out=example_client \ --pyi_out=example_client \ google/cloud/universalledger/v1/transactions.protopython-grpc-tools-protoc --proto_path=googleapis/ \ --python_out=example_client \ --pyi_out=example_client \ google/cloud/universalledger/v1/types.protopython-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: 범용 원장 엔드포인트가 있는 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 디렉터리로 이동합니다.
설정 단계에서 가상 환경이 활성 상태여야 합니다.
스크립트 디렉터리로 변경합니다.
cd example_client셸 프롬프트에서 가상 환경이 활성화되었는지 확인해야 합니다(예:
(example_client)로 시작).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
다음 단계
- 범용 원장 API의 모든 메서드를 참고하세요.
- 다른 언어의 gRPC 지원에 대해 알아봅니다.
- 범용 원장 API 프로토콜 버퍼 정의를 살펴봅니다.