CTS 用戶端程式庫

本頁說明如何開始使用 Cloud Talent Solution API 適用的 Cloud 用戶端程式庫。有了用戶端程式庫,您可以透過支援的語言,更輕鬆地存取 Google Cloud Platform API。雖然您可以直接向伺服器發出原始要求來使用 Google Cloud Platform API,但用戶端程式庫提供簡化功能,可大幅減少需要編寫的程式碼數量。

如要進一步瞭解 Cloud 用戶端程式庫和舊版 Google API 用戶端程式庫,請參閱「用戶端程式庫說明」。

我們即將推出更多語言版本的用戶端程式庫。

安裝用戶端程式庫

C#

如果是使用 Visual Studio 2017 以上版本,請開啟 NuGet 套件管理工具視窗,然後輸入下列內容:

Install-Package Google.Apis

如果是使用 .NET Core 指令列介面工具安裝依附元件,請執行下列指令:

dotnet add package Google.Apis

詳情請參閱「設定 C# 開發環境」。

Go

go get google.golang.org/api/jobs/v3p1beta1

詳情請參閱「設定 Go 開發環境」。

Java

如果您使用 Maven,請在 pom.xml 檔案中加入以下指令:

<dependency>
    <groupId>com.google.apis</groupId>
    <artifactId>google-api-services-jobs</artifactId>
    <version>LATEST</version>
</dependency>

詳情請參閱「設定 Java 開發環境」。

Node.js

npm install googleapis

詳情請參閱「設定 Node.js 開發環境」。

PHP

composer require google/apiclient

詳情請參閱「在 Google Cloud 上使用 PHP」。

Python

pip install --upgrade google-api-python-client

詳情請參閱「設定 Python 開發環境」。

Ruby

gem install google-api-client

詳情請參閱「設定 Ruby 開發環境」。

設定驗證方法

為驗證向 Google Cloud Platform API 發出的呼叫,用戶端程式庫支援應用程式預設憑證 (ADC);程式庫會在定義的一組位置中尋找憑證,並使用這些憑證驗證向 API 發出的要求。有了 ADC,無需修改應用程式程式碼,就能在各種環境 (例如本機開發環境或正式環境),為應用程式提供憑證。

在正式環境中,設定 ADC 的方式取決於服務和背景。詳情請參閱「設定應用程式預設憑證」。

在本機開發環境中,您可以使用與 Google 帳戶相關聯的憑證設定 ADC:

  1. Install the Google Cloud CLI. After installation, initialize the Google Cloud CLI by running the following command:

    gcloud init

    If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  2. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

    登入畫面會隨即顯示。登入後,您的憑證會儲存在 ADC 使用的本機憑證檔案中。

使用用戶端程式庫

以下範例將說明用戶端程式庫的使用方法。

Go


// Command quickstart is an example of using the Google Cloud Talent Solution API.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"golang.org/x/oauth2/google"
	talent "google.golang.org/api/jobs/v3"
)

func main() {
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	parent := fmt.Sprintf("projects/%s", projectID)

	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		log.Fatal(err)
	}

	// Create the jobs service client.
	ctsService, err := talent.New(client)
	if err != nil {
		log.Fatal(err)
	}

	// Make the RPC call.
	response, err := ctsService.Projects.Companies.List(parent).Do()
	if err != nil {
		log.Fatalf("Failed to list Companies: %v", err)
	}

	// Print the request id.
	fmt.Printf("Request ID: %q\n", response.Metadata.RequestId)

	// Print the returned companies.
	for _, company := range response.Companies {
		fmt.Printf("Company: %q\n", company.Name)
	}
}

Java


private static final JsonFactory JSON_FACTORY = new GsonFactory();
private static final NetHttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
private static final String DEFAULT_PROJECT_ID =
    "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");

private static CloudTalentSolution talentSolutionClient =
    createTalentSolutionClient(generateCredential());

private static CloudTalentSolution createTalentSolutionClient(GoogleCredentials credential) {
  String url = "https://jobs.googleapis.com";

  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  return new CloudTalentSolution.Builder(NET_HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("JobServiceClientSamples")
      .setRootUrl(url)
      .build();
}

private static GoogleCredentials generateCredential() {
  try {
    // Credentials could be downloaded after creating service account
    // set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable, for example:
    // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
    return GoogleCredentials.getApplicationDefault()
        .createScoped(Collections.singleton(CloudTalentSolutionScopes.JOBS));
  } catch (Exception e) {
    System.out.println("Error in generating credential");
    throw new RuntimeException(e);
  }
}

public static CloudTalentSolution getTalentSolutionClient() {
  return talentSolutionClient;
}

public static void main(String... args) throws Exception {
  try {
    ListCompaniesResponse listCompaniesResponse =
        talentSolutionClient.projects().companies().list(DEFAULT_PROJECT_ID).execute();
    System.out.println("Request Id is " + listCompaniesResponse.getMetadata().getRequestId());
    if (listCompaniesResponse.getCompanies() != null) {
      for (Company company : listCompaniesResponse.getCompanies()) {
        System.out.println(company.getName());
      }
    }
  } catch (IOException e) {
    System.out.println("Got exception while listing companies");
    throw e;
  }
}

Node.js

Python

其他資源

C#

下方列出與 C# 用戶端程式庫相關的其他資源連結:

Go

下方列出與 Go 用戶端程式庫相關的其他資源連結:

Java

下方列出與 Java 用戶端程式庫相關的其他資源連結:

Node.js

下方列出與 Node.js 用戶端程式庫相關的其他資源連結:

PHP

下方列出與 PHP 用戶端程式庫相關的其他資源連結:

Python

下方列出與 Python 用戶端程式庫相關的其他資源連結:

Ruby

下方列出與 Ruby 用戶端程式庫相關的其他資源連結: