Analytics Hub 클라이언트 라이브러리

이 페이지에서는 Analytics Hub API에 대해 Cloud 클라이언트 라이브러리를 시작하는 방법을 보여줍니다. 클라이언트 라이브러리를 사용하면 지원되는 언어로 Google Cloud API에 쉽게 액세스할 수 있습니다. 원시 요청을 서버에 보내 Google Cloud API를 직접 사용할 수 있지만 클라이언트 라이브러리는 작성해야 하는 코드 양을 크게 줄여 주는 간소화 기능을 제공합니다.

클라이언트 라이브러리 설명에서 Cloud 클라이언트 라이브러리 및 이전 Google API 클라이언트 라이브러리에 대해 자세히 알아보세요.

클라이언트 라이브러리 설치

C#

Install-Package Google.Cloud.BigQuery.AnalyticsHub.V1 -Pre

자세한 내용은 C# 개발 환경 설정을 참조하세요.

Go

go get cloud.google.com/go/bigquery

자세한 내용은 Go 개발 환경 설정을 참조하세요.

Java

자세한 내용은 자바 개발 환경 설정을 참조하세요.

Node.js

npm install @google-cloud/bigquery-data-exchange

자세한 내용은 Node.js 개발 환경 설정을 참조하세요.

PHP

composer require google/cloud-bigquery-analyticshub

자세한 내용은 Google Cloud에서 PHP 사용을 참조하세요.

Python

pip install --upgrade google-cloud-bigquery-analyticshub

자세한 내용은 Python 개발 환경 설정을 참조하세요.

Ruby

gem install google-cloud-bigquery-analytics_hub-v1

자세한 내용은 Ruby 개발 환경 설정을 참조하세요.

인증 설정

Google Cloud API 호출을 인증하기 위해 클라이언트 라이브러리는 애플리케이션 기본 사용자 인증 정보(ADC)를 지원합니다. 라이브러리가 정의된 위치 집합에서 사용자 인증 정보를 찾고 이러한 사용자 인증 정보를 사용하여 API에 대한 요청을 인증합니다. ADC를 사용하면 애플리케이션 코드를 수정할 필요 없이 로컬 개발 또는 프로덕션과 같은 다양한 환경에서 애플리케이션에 사용자 인증 정보를 제공할 수 있습니다.

프로덕션 환경에서 ADC를 설정하는 방법은 서비스와 컨텍스트에 따라 다릅니다. 자세한 내용은 애플리케이션 기본 사용자 인증 정보 설정을 참조하세요.

로컬 개발 환경의 경우 Google 계정과 연결된 사용자 인증 정보를 사용하여 ADC를 설정할 수 있습니다.

  1. gcloud CLI를 설치하고 초기화합니다.

    gcloud CLI를 초기화할 때 애플리케이션에 필요한 리소스에 액세스할 수 있는 권한이 있는 Google Cloud 프로젝트를 지정해야 합니다.

  2. ADC를 구성합니다.

    gcloud auth application-default login

    로그인 화면이 표시됩니다. 로그인 후 사용자 인증 정보는 ADC에 사용하는 로컬 사용자 인증 정보 파일에 저장됩니다.

클라이언트 라이브러리 사용

다음 예시는 Analytics Hub와의 기본적인 상호작용을 보여줍니다.

Go

// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.


// The analyticshub quickstart application demonstrates usage of the
// Analytics hub API by creating an example data exchange and listing.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"

	dataexchange "cloud.google.com/go/bigquery/dataexchange/apiv1beta1"
	dataexchangepb "google.golang.org/genproto/googleapis/cloud/bigquery/dataexchange/v1beta1"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

func main() {

	// Define the command line flags for controlling the behavior of this quickstart.
	var (
		projectID            = flag.String("project_id", "", "Cloud Project ID, used for session creation.")
		location             = flag.String("location", "US", "BigQuery location used for interactions.")
		exchangeID           = flag.String("exchange_id", "ExampleDataExchange", "identifier of the example data exchange")
		listingID            = flag.String("listing_id", "ExampleDataExchange", "identifier of the example data exchange")
		exampleDatasetSource = flag.String("dataset_source", "", "dataset source in the form projects/myproject/datasets/mydataset")
		delete               = flag.Bool("delete_exchange", true, "delete exchange at the end of quickstart")
	)
	flag.Parse()
	// Perform simple validation of the specified flags.
	if *projectID == "" {
		log.Fatal("empty --project_id specified, please provide a valid project ID")
	}
	if *exampleDatasetSource == "" {
		log.Fatalf("empty --dataset_source specified, please provide in the form \"projects/myproject/datasets/mydataset\"")
	}

	// Instantiate the client.
	ctx := context.Background()
	dataExchClient, err := dataexchange.NewAnalyticsHubClient(ctx)
	if err != nil {
		log.Fatalf("NewClient: %v", err)
	}
	defer dataExchClient.Close()

	// Then, create the data exchange (or return information about one already bearing the example name), and
	// print information about it.
	exchange, err := createOrGetDataExchange(ctx, dataExchClient, *projectID, *location, *exchangeID)
	if err != nil {
		log.Fatalf("failed to get information about the exchange: %v", err)
	}
	fmt.Printf("\nData Exchange Information\n")
	fmt.Printf("Exchange Name: %s\n", exchange.GetName())
	if desc := exchange.GetDescription(); desc != "" {
		fmt.Printf("Exchange Description: %s", desc)
	}

	// Finally, create a listing within the data exchange and print information about it.
	listing, err := createListing(ctx, dataExchClient, *projectID, *location, *exchangeID, *listingID, *exampleDatasetSource)
	if err != nil {
		log.Fatalf("failed to create the listing within the exchange: %v", err)
	}
	fmt.Printf("\n\nListing Information\n")
	fmt.Printf("Listing Name: %s\n", listing.GetName())
	if desc := listing.GetDescription(); desc != "" {
		fmt.Printf("Listing Description: %s\n", desc)
	}
	fmt.Printf("Listing State: %s\n", listing.GetState().String())
	if source := listing.GetSource(); source != nil {
		if dsSource, ok := source.(*dataexchangepb.Listing_BigqueryDataset); ok && dsSource.BigqueryDataset != nil {
			if dataset := dsSource.BigqueryDataset.GetDataset(); dataset != "" {
				fmt.Printf("Source is a bigquery dataset: %s", dataset)
			}
		}
	}
	// Optionally, delete the data exchange at the end of the quickstart to clean up the resources used.
	if *delete {
		fmt.Printf("\n\n")
		if err := deleteDataExchange(ctx, dataExchClient, *projectID, *location, *exchangeID); err != nil {
			log.Fatalf("failed to delete exchange: %v", err)
		}
		fmt.Printf("Exchange projects/%s/locations/%s/dataExchanges/%s was deleted.\n", *projectID, *location, *exchangeID)
	}
	fmt.Printf("\nQuickstart completed.\n")
}

// createOrGetDataExchange creates an example data exchange, or returns information about the exchange already bearing
// the example identifier.
func createOrGetDataExchange(ctx context.Context, client *dataexchange.AnalyticsHubClient, projectID, location, exchangeID string) (*dataexchangepb.DataExchange, error) {
	req := &dataexchangepb.CreateDataExchangeRequest{
		Parent:         fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		DataExchangeId: exchangeID,
		DataExchange: &dataexchangepb.DataExchange{
			DisplayName:    "Example Data Exchange",
			Description:    "Exchange created as part of an API quickstart",
			PrimaryContact: "",
			Documentation:  "https://link.to.optional.documentation/",
		},
	}

	resp, err := client.CreateDataExchange(ctx, req)
	if err != nil {
		// We'll handle one specific error case specially, the case of the exchange already existing.  In this instance,
		// we'll issue a second request to fetch the exchange information for the already present exchange and return it.
		if code := status.Code(err); code == codes.AlreadyExists {
			getReq := &dataexchangepb.GetDataExchangeRequest{
				Name: fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, location, exchangeID),
			}
			resp, err = client.GetDataExchange(ctx, getReq)
			if err != nil {
				return nil, fmt.Errorf("error getting dataExchange: %w", err)
			}
			return resp, nil
		}
		// For all other cases, return the error from creation request.
		return nil, err
	}
	return resp, nil
}

// createListing creates an example listing within the specified exchange using the provided source dataset.
func createListing(ctx context.Context, client *dataexchange.AnalyticsHubClient, projectID, location, exchangeID, listingID, sourceDataset string) (*dataexchangepb.Listing, error) {
	req := &dataexchangepb.CreateListingRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, location, exchangeID),
		ListingId: listingID,
		Listing: &dataexchangepb.Listing{
			DisplayName: "Example Exchange Listing",
			Description: "Example listing created as part of an API quickstart",
			Categories: []dataexchangepb.Listing_Category{
				dataexchangepb.Listing_CATEGORY_OTHERS,
			},
			Source: &dataexchangepb.Listing_BigqueryDataset{
				BigqueryDataset: &dataexchangepb.Listing_BigQueryDatasetSource{
					Dataset: sourceDataset,
				},
			},
		},
	}
	return client.CreateListing(ctx, req)
}

// deleteDataExchange deletes a data exchange.
func deleteDataExchange(ctx context.Context, client *dataexchange.AnalyticsHubClient, projectID, location, exchangeID string) error {
	req := &dataexchangepb.DeleteDataExchangeRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/dataExchanges/%s", projectID, location, exchangeID),
	}
	return client.DeleteDataExchange(ctx, req)
}

Node.js

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. The parent resource path of the DataExchanges.
 *  e.g. `projects/myproject/locations/US`.
 */
// const parent = 'abc123'
/**
 *  The maximum number of results to return in a single response page. Leverage
 *  the page tokens to iterate through the entire collection.
 */
// const pageSize = 1234
/**
 *  Page token, returned by a previous call, to request the next page of
 *  results.
 */
// const pageToken = 'abc123'

// Imports the Dataexchange library
const {AnalyticsHubServiceClient} =
  require('@google-cloud/bigquery-data-exchange').v1beta1;

// Instantiates a client
const dataexchangeClient = new AnalyticsHubServiceClient();

async function callListDataExchanges() {
  // Construct request
  const request = {
    parent,
  };

  // Run request
  const iterable = await dataexchangeClient.listDataExchangesAsync(request);
  for await (const response of iterable) {
    console.log(response);
  }
}

callListDataExchanges();

추가 리소스

C#

다음 목록에는 C#용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Go

다음 목록에는 Go용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Java

다음 목록에는 자바용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Node.js

다음 목록에는 Node.js용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

PHP

다음 목록에는 PHP용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Python

다음 목록에는 Python용 클라이언트 라이브러리와 관련된 추가 리소스에 대한 링크가 포함되어 있습니다.

Ruby

다음 목록에는 Ruby용 클라이언트 라이브러리와 관련된 추가 리소스의 링크가 포함되어 있습니다.

다음 단계

자세한 배경 정보는 Analytics Hub 소개를 참조하세요.