CTS Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Talent Solution API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Client libraries for more languages are coming soon.

Installing the client library

Go

go get -u google.golang.org/api/jobs/v4

Java

For more information, see Setting Up a Java Development Environment. If you are using Maven, add the following to your pom.xml file:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-talent</artifactId>
  <version>0.17.0-beta</version>
</dependency>
If you are using Gradle, add the following to your dependencies:
compile 'com.google.cloud:google-cloud-talent:0.17.0-beta'
If you are using SBT, add the following to your dependencies:
libraryDependencies += "com.google.cloud" % "google-cloud-talent" % "0.17.0-beta"

If you're using IntelliJ or Eclipse, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save googleapis

PHP

composer require google/apiclient

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-api-python-client

Ruby

For more information, see Setting Up a Ruby Development Environment.
gem install google-api-client

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

GCP Console

  1. In the GCP Console, go to the Create service account key page.

    Go to the Create Service Account Key page
  2. From the Service account list, select New service account.
  3. In the Service account name field, enter a name.
  4. From the Role list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using the GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Command line

You can run the following commands using the Cloud SDK on your local machine, or in Cloud Shell.

  1. Create the service account. Replace [NAME] with a name for the service account.

    gcloud iam service-accounts create [NAME]
  2. Grant permissions to the service account. Replace [PROJECT_ID] with your project ID.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later by using GCP Console. If you are developing a production app, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. Replace [FILE_NAME] with a name for the key file.

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

With command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

Go

import (
	"context"
	"fmt"
	"os"

	talent "cloud.google.com/go/talent/apiv4beta1"
	"google.golang.org/api/iterator"
	talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1"
)

func main() {
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")

	// Initialize job search client.
	ctx := context.Background()
	c, err := talent.NewCompanyClient(ctx)
	if err != nil {
		fmt.Printf("talent.NewCompanyClient: %v", err)
		return
	}

	// Construct a listCompany request.
	req := &talentpb.ListCompaniesRequest{
		Parent: "projects/" + projectID,
	}

	it := c.ListCompanies(ctx, req)

	for {
		resp, err := it.Next()
		if err == iterator.Done {
			fmt.Printf("Done.\n")
			break
		}
		if err != nil {
			fmt.Printf("it.Next: %v", err)
			return
		}
		fmt.Printf("Company: %v\n", resp.GetName())
	}
}

Java

/*
 * Please include the following imports to run this sample.
 *
 * import com.google.cloud.talent.v4beta1.Company;
 * import com.google.cloud.talent.v4beta1.CompanyServiceClient;
 * import com.google.cloud.talent.v4beta1.ListCompaniesRequest;
 * import com.google.cloud.talent.v4beta1.TenantName;
 * import com.google.cloud.talent.v4beta1.TenantOrProjectName;
 */

/**
 * List Companies
 *
 * @param projectId Your Google Cloud Project ID
 * @param tenantId Identifier of the Tenant
 */
public static void sampleListCompanies(String projectId, String tenantId) {
  try (CompanyServiceClient companyServiceClient = CompanyServiceClient.create()) {
    // projectId = "Your Google Cloud Project ID";
    // tenantId = "Your Tenant ID (using tenancy is optional)";
    TenantOrProjectName parent = TenantName.of(projectId, tenantId);
    ListCompaniesRequest request =
        ListCompaniesRequest.newBuilder().setParent(parent.toString()).build();
    for (Company responseItem : companyServiceClient.listCompanies(request).iterateAll()) {
      System.out.printf("Company Name: %s\n", responseItem.getName());
      System.out.printf("Display Name: %s\n", responseItem.getDisplayName());
      System.out.printf("External ID: %s\n", responseItem.getExternalId());
    }
  } catch (Exception exception) {
    System.err.println("Failed to create the client due to: " + exception);
  }
}

Node.js


const talent = require('@google-cloud/talent').v4beta1;

/**
 * List Companies
 *
 * @param projectId {string} Your Google Cloud Project ID
 * @param tenantId {string} Identifier of the Tenant
 */
function sampleListCompanies(projectId, tenantId) {
  const client = new talent.CompanyServiceClient();
  // Iterate over all elements.
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  const formattedParent = client.tenantPath(projectId, tenantId);

  client.listCompanies({parent: formattedParent})
    .then(responses => {
      const resources = responses[0];
      for (const resource of resources) {
        console.log(`Company Name: ${resource.name}`);
        console.log(`Display Name: ${resource.displayName}`);
        console.log(`External ID: ${resource.externalId}`);
      }
    })
    .catch(err => {
      console.error(err);
    });
}

PHP

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Talent\V4beta1\CompanyServiceClient;

/**
 * List Companies.
 *
 * @param string $projectId Your Google Cloud Project ID
 * @param string $tenantId  Identifier of the Tenant
 */
function sampleListCompanies($projectId, $tenantId)
{

    $companyServiceClient = new CompanyServiceClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    $formattedParent = $companyServiceClient->tenantName($projectId, $tenantId);

    try {
        // Iterate through all elements
        $pagedResponse = $companyServiceClient->listCompanies($formattedParent);
        foreach ($pagedResponse->iterateAllElements() as $responseItem) {
            printf('Company Name: %s'.PHP_EOL, $responseItem->getName());
            printf('Display Name: %s'.PHP_EOL, $responseItem->getDisplayName());
            printf('External ID: %s'.PHP_EOL, $responseItem->getExternalId());
        }
    } finally {
        $companyServiceClient->close();
    }

}

Python


from google.cloud import talent_v4beta1
import six


def sample_list_companies(project_id, tenant_id):
    """List Companies"""

    client = talent_v4beta1.CompanyServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'

    if isinstance(project_id, six.binary_type):
        project_id = project_id.decode('utf-8')
    if isinstance(tenant_id, six.binary_type):
        tenant_id = tenant_id.decode('utf-8')
    parent = client.tenant_path(project_id, tenant_id)

    # Iterate over all results
    for response_item in client.list_companies(parent):
        print('Company Name: {}'.format(response_item.name))
        print('Display Name: {}'.format(response_item.display_name))
        print('External ID: {}'.format(response_item.external_id))


Ruby


 # List Companies
 #
 # @param project_id {String} Your Google Cloud Project ID
 # @param tenant_id {String} Identifier of the Tenant
def sample_list_companies(project_id, tenant_id)
  # Instantiate a client
  company_client = Google::Cloud::Talent::CompanyService.new version: :v4beta1

  # project_id = "Your Google Cloud Project ID"
  # tenant_id = "Your Tenant ID (using tenancy is optional)"
  formatted_parent = company_client.class.tenant_path(project_id, tenant_id)

  # Iterate over all results.
  company_client.list_companies(formatted_parent).each do |element|
    puts "Company Name: #{element.name}"
    puts "Display Name: #{element.display_name}"
    puts "External ID: #{element.external_id}"
  end

end

Additional resources

Czy ta strona była pomocna? Podziel się z nami swoją opinią:

Wyślij opinię na temat...

Job search documentation
Potrzebujesz pomocy? Odwiedź naszą stronę wsparcia.