Quickstart: Create companies and jobs (v3)

This tutorial is designed to get you started exploring and developing applications with Cloud Talent Solution. Familiarity with basic programming is assumed, though even without much programming knowledge, you should be able to follow along. After going through this tutorial, you should be able to use the Reference documentation to create your own basic applications.

This tutorial steps through a Cloud Talent Solution application using Java code. The purpose here is not to explain the Java client libraries, but to explain how to make calls to Cloud Talent Solution. Applications in Python and Node.js are essentially similar. Please contact us if you have any questions.

Prerequisites

You have:

Create a company with jobs and search for those jobs

This tutorial walks you through a basic Cloud Talent Solution application, and guides you through creating a single job that you associate to a company. The next tutorial walks you through the steps to search for jobs within the company based on attributes of the jobs and the search query. The search API attempts to return jobs most relevant to a job seeker's query based on available fields within a job (company name, job title, job description, job categories, job location, etc.).

Create service with your credentials

Create the service with the JSON credential file you downloaded in Before You Begin:

Java

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


private static final JsonFactory JSON_FACTORY = new JacksonFactory();
private static final NetHttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
private static final String SCOPES = "https://www.googleapis.com/auth/jobs";
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 = new HttpCredentialsAdapter(credential);
  return new CloudTalentSolution.Builder(
          NET_HTTP_TRANSPORT, JSON_FACTORY, setHttpTimeout(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(SCOPES));
  } catch (Exception e) {
    System.out.print("Error in generating credential");
    throw new RuntimeException(e);
  }
}

private static HttpRequestInitializer setHttpTimeout(
    final HttpRequestInitializer requestInitializer) {
  return request -> {
    requestInitializer.initialize(request);
    request.setHeaders(new HttpHeaders().set("X-GFE-SSL", "yes"));
    request.setConnectTimeout(1 * 60000); // 1 minute connect timeout
    request.setReadTimeout(1 * 60000); // 1 minute read timeout
  };
}

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;
  }
}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

import os

from googleapiclient.discovery import build
from googleapiclient.errors import Error

client_service = build('jobs', 'v3')


def run_sample():
    try:
        project_id = 'projects/' + os.environ['GOOGLE_CLOUD_PROJECT']
        response = client_service.projects().companies().list(
            parent=project_id).execute()
        print('Request Id: %s' %
              response.get('metadata').get('requestId'))
        print('Companies:')
        if response.get('companies') is not None:
            for company in response.get('companies'):
                print('%s' % company.get('name'))
        print('')

    except Error as e:
        print('Got exception while listing companies')
        raise e


if __name__ == '__main__':
    run_sample()

C#

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using Google.Apis.CloudTalentSolution.v3;
using Google.Apis.CloudTalentSolution.v3.Data;
using System.Linq;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static GoogleCredential credential;
        public static CloudTalentSolutionService jobServiceClient;
        public static string projectId;
        public static string parent;

        public static void Main(string[] args)
        {
            // Authorize the client using Application Default Credentials.
            // See: https://developers.google.com/identity/protocols/application-default-credentials
            credential = GoogleCredential.GetApplicationDefaultAsync().Result;
            // Specify the Service scope.
            if (credential.IsCreateScopedRequired)
            {
                credential = credential.CreateScoped(new[]
                {
                    Google.Apis.CloudTalentSolution.v3.CloudTalentSolutionService.Scope.Jobs
                });
            }
            // Instantiate the Cloud Key Management Service API.
            jobServiceClient = new CloudTalentSolutionService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                GZipEnabled = false
            });

            projectId = Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
            parent = $"projects/{projectId}";

            // List companies.
            ListCompaniesResponse result = jobServiceClient.Projects.Companies.List(parent).Execute();
            Console.WriteLine("Request Id: " + result.Metadata.RequestId);
            if (result.Companies != null)
            {
                Console.WriteLine("Companies: ");
                result.Companies.ToList().ForEach(company => Console.WriteLine(company.Name));
            }
            else { Console.WriteLine("No companies found."); }
        }
    }
}

Go

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


// 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)
	}
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


// Imports the Google APIs client library
const {google} = require('googleapis');

const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT;

// Acquires credentials
google.auth.getApplicationDefault((err, authClient) => {
  if (err) {
    console.error('Failed to acquire credentials');
    console.error(err);
    return;
  }

  if (authClient.createScopedRequired && authClient.createScopedRequired()) {
    authClient = authClient.createScoped([
      'https://www.googleapis.com/auth/jobs',
    ]);
  }

  // Instantiates an authorized client
  const jobServiceClient = google.jobs({
    version: 'v3',
    auth: authClient,
  });

  const request = {
    parent: `projects/${PROJECT_ID}`,
  };

  // Lists companies
  jobServiceClient.projects.companies.list(request, (err, result) => {
    if (err) {
      console.error(`Failed to retrieve companies! ${err}`);
      throw err;
    }

    console.log(`Request ID: ${result.data.metadata.requestId}`);

    const companies = result.data.companies || [];

    if (companies.length) {
      console.log('Companies:');
      companies.forEach((company) => console.log(company.name));
    } else {
      console.log(`No companies found.`);
    }
  });
});

Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

require "google/apis/jobs_v3"
require "rails"

# Instantiate the client
Jobs = Google::Apis::JobsV3
jobs_client = Jobs::CloudTalentSolutionService.new

# @see https://developers.google.com/identity/protocols/application-default-credentials#callingruby
jobs_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)

# ProjectId to get company list
DEFAULT_PROJECT_ID = "projects/" + ENV["GOOGLE_CLOUD_PROJECT"]
# Request list of companies
response = jobs_client.list_project_companies DEFAULT_PROJECT_ID

# Print the request id
puts "Request id : " + response.metadata.request_id

# List all companies for your project
puts "Companies: "
if response.companies
  response.companies.each do |company|
    puts company.name
  end
else
  puts "No companies found"
end

This code configures the client service with your application's credential information. The OAuth 2.0 request is sent when an API call is made. The auth token generated using the process above typically has an expiration date of 1 hour, after which you'll get an error if you try to use it. The GoogleCredential library takes care of automatically "refreshing" the token which simply means getting a new access token.

Create company

A company is an entity associated with a set of job listings. You must create the company before you can post jobs on Cloud Talent Solution for that company. You can send any freeform string as the externalId when creating the company. This means you can use the primary key from your existing database (if you have one) when creating and referring to a company.

Java

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/** Create a company. */
public static Company createCompany(Company companyToBeCreated) throws IOException {
  try {
    CreateCompanyRequest createCompanyRequest =
        new CreateCompanyRequest().setCompany(companyToBeCreated);
    Company companyCreated =
        talentSolutionClient
            .projects()
            .companies()
            .create(DEFAULT_PROJECT_ID, createCompanyRequest)
            .execute();
    System.out.println("Company created: " + companyCreated);
    return companyCreated;
  } catch (IOException e) {
    System.out.println("Got exception while creating company");
    throw e;
  }
}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

def create_company(client_service, company_to_be_created):
    try:
        request = {'company': company_to_be_created}
        company_created = client_service.projects().companies().create(
            parent=parent, body=request).execute()
        print('Company created: %s' % company_created)
        return company_created
    except Error as e:
        print('Got exception while creating company')
        raise e

C#

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


public static Company CreateCompany(Company companyToBeCreated)
{
    try
    {
        CreateCompanyRequest createCompanyRequest = new CreateCompanyRequest();
        createCompanyRequest.Company = companyToBeCreated;
        Company companyCreated = jobServiceClient.Projects.Companies.Create(createCompanyRequest, parent).Execute();
        Console.WriteLine("Created company: " + ToJsonString(companyCreated));
        return companyCreated;
    }
    catch (Exception e)
    {
        Console.WriteLine("Got exception while creating company");
        throw e;
    }
}

Go

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


// createCompany creates a company as given.
func createCompany(w io.Writer, projectID string, companyToCreate *talent.Company) (*talent.Company, error) {
	ctx := context.Background()

	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %v", err)
	}

	parent := "projects/" + projectID
	req := &talent.CreateCompanyRequest{
		Company: companyToCreate,
	}
	company, err := service.Projects.Companies.Create(parent, req).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to create company %q: %v", companyToCreate.DisplayName, err)
	}

	return company, nil
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/**
 * Create a company.
 */
const createCompany = async (jobServiceClient, companyToBeCreated) => {
  try {
    const request = {
      parent: `projects/${PROJECT_ID}`,
      resource: {
        company: companyToBeCreated,
      },
    };

    const companyCreated = await jobServiceClient.projects.companies.create(
      request
    );

    console.log(`Company created: ${JSON.stringify(companyCreated.data)}`);
    return companyCreated.data;
  } catch (e) {
    console.error(`Failed to create company! ${e}`);
    throw e;
  }
};

Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

# project_id              = "Id of the project"
# company_to_be_created   = "Company to be created"

require "google/apis/jobs_v3"

jobs = Google::Apis::JobsV3
talent_solution_client = jobs::CloudTalentSolutionService.new
# @see
# https://developers.google.com/identity/protocols/application-default-credentials#callingruby
talent_solution_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)

begin
  create_company_request = jobs::CreateCompanyRequest.new company: company_to_be_created
  company_created = talent_solution_client.create_company project_id, create_company_request
  puts "Company created: #{company_created.to_json}"
  return company_created
rescue StandardError => e
  puts "Exception occurred while creating company: #{e}"
end

Get company

You can read the present state of a company by sending a GET request, along with the name of the company assigned by our backend.

Java

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/** Get a company. */
public static Company getCompany(String companyName) throws IOException {
  try {
    Company companyExisted =
        talentSolutionClient.projects().companies().get(companyName).execute();
    System.out.println("Company existed: " + companyExisted);
    return companyExisted;
  } catch (IOException e) {
    System.out.println("Got exception while getting company");
    throw e;
  }
}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

def get_company(client_service, company_name):
    try:
        company_existed = client_service.projects().companies().get(
            name=company_name).execute()
        print('Company existed: %s' % company_existed)
        return company_existed
    except Error as e:
        print('Got exception while getting company')
        raise e

C#

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


public static Company GetCompany(string companyName)
{
    try
    {
        Company companyExisted = jobServiceClient.Projects.Companies.Get(companyName).Execute();
        Console.WriteLine("Company existed: " + companyExisted.Name);
        return companyExisted;
    }
    catch (Exception e)
    {
        Console.WriteLine("Got exception while getting company");
        throw e;
    }
}

Go

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


// getCompany gets an existing company by name.
func getCompany(w io.Writer, name string) (*talent.Company, error) {
	ctx := context.Background()

	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %v", err)
	}

	company, err := service.Projects.Companies.Get(name).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to get company %q: %v", name, err)
	}

	fmt.Fprintf(w, "Company: %q\n", company.Name)

	return company, nil
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/**
 * Get a company.
 */
const getCompany = async (jobServiceClient, companyName) => {
  try {
    const request = {
      name: companyName,
    };

    const companyExisted = await jobServiceClient.projects.companies.get(
      request
    );

    console.log(`Company existed: ${JSON.stringify(companyExisted.data)}`);
    return companyExisted.data;
  } catch (e) {
    console.error('Got exception while getting company');
    throw e;
  }
};

Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

# company_name  = "The name of the company you want to get. The format is "projects/{project_id}/companies/{company_id}""

require "google/apis/jobs_v3"

jobs = Google::Apis::JobsV3
talent_solution_client = jobs::CloudTalentSolutionService.new
# @see
# https://developers.google.com/identity/protocols/application-default-credentials#callingruby
talent_solution_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)

begin
  company_got = talent_solution_client.get_project_company company_name
  puts "Company got: #{company_got.to_json}"
  return company_got
rescue StandardError => e
  puts "Exception occurred while getting company: #{e}"
end

Create job

To post a new job, you must provide all of the required fields about the new job along with the companyName of the company you want to associate this job with, which you specified when you created the company resource.

The data object with the job data filled in is sent to the Cloud Talent Solution endpoint using a POST request. Note that the name field should not be set in the initial request since it is an "output only" field of the createJob API and is a part of the API response when a new job entity is created by the server. The API endpoint to interact with the jobs resource is specified in the Cloud Talent Solution Client Libraries document.

The response to the request is an object of the new job posting; it should include a job name which uniquely represents the posting. The job name is used when the posting needs to be updated or deleted. As a best practice, store this name and map it to your own unique ID for the job.

The server returns an error if you attempt to insert a job when another job already exists on the system with the same companyName, requisitionId and languageCode for the same company.

The following code creates a job with just the required fields for the company specified in the companyName field.

Java

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/** Create a job. */
public static Job createJob(Job jobToBeCreated) throws IOException {
  try {
    CreateJobRequest createJobRequest = new CreateJobRequest().setJob(jobToBeCreated);

    Job jobCreated =
        talentSolutionClient
            .projects()
            .jobs()
            .create(DEFAULT_PROJECT_ID, createJobRequest)
            .execute();
    System.out.println("Job created: " + jobCreated);
    return jobCreated;
  } catch (IOException e) {
    System.out.println("Got exception while creating job");
    throw e;
  }
}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

def create_job(client_service, job_to_be_created):
    try:
        request = {'job': job_to_be_created}
        job_created = client_service.projects().jobs().create(
            parent=parent, body=request).execute()
        print('Job created: %s' % job_created)
        return job_created
    except Error as e:
        print('Got exception while creating job')
        raise e

C#

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


public static Job CreateJob(Job jobToBeCreated)
{
    try
    {
        CreateJobRequest createJobRequest = new CreateJobRequest();
        createJobRequest.Job = jobToBeCreated;

        Job jobCreated = jobServiceClient.Projects.Jobs.Create(createJobRequest, parent).Execute();
        Console.WriteLine("Job created: " + jobCreated.Name);
        return jobCreated;
    }
    catch (Exception e)
    {
        Console.WriteLine("Got exception while creating job");
        throw e;
    }
}

Go

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


// createJob create a job as given.
func createJob(w io.Writer, projectID string, jobToCreate *talent.Job) (*talent.Job, error) {
	ctx := context.Background()

	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %v", err)
	}

	parent := "projects/" + projectID
	req := &talent.CreateJobRequest{
		Job: jobToCreate,
	}
	job, err := service.Projects.Jobs.Create(parent, req).Do()
	if err != nil {
		return nil, fmt.Errorf("Failed to create job %q, Err: %v", jobToCreate.RequisitionId, err)
	}
	return job, err
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/**
 * Create a job.
 */
const createJob = async (jobServiceClient, jobToBeCreated) => {
  try {
    const request = {
      parent: `projects/${PROJECT_ID}`,
      resource: {
        job: jobToBeCreated,
      },
    };

    const jobCreated = await jobServiceClient.projects.jobs.create(request);

    console.log(`Job created: ${JSON.stringify(jobCreated.data)}`);
    return jobCreated.data;
  } catch (e) {
    console.error(`Got exception while creating job!`);
    throw e;
  }
};

Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

# project_id         = "Id of the project"
# job_to_be_created  = "Job to be created"

require "google/apis/jobs_v3"

jobs = Google::Apis::JobsV3

talent_solution_client = jobs::CloudTalentSolutionService.new
talent_solution_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)

begin
  create_job_request = jobs::CreateJobRequest.new job: job_to_be_created
  job_created = talent_solution_client.create_job project_id, create_job_request
  puts "Job created: #{job_created.to_json}"
  return job_created
rescue StandardError => e
  puts "Exception occurred while creating job: #{e}"
end

Cloud Talent Solution also allows you to create jobs that are specific to a location. See locations for more information.

Cloud Talent Solution has several fields associated with a job that are built in to the API schema. However, you might still have some fields that aren't a part of the out-of-the-box fields. While it is recommended that all customers of Cloud Talent Solution always use the out-of-the box fields wherever possible, Cloud Talent Solution also provides some customAttributes for a job. These might be filterable or non-filterable. Refer to the customAttributes for more information.

The following code example shows how to create a job with a customAttribute:

Java

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/** Generate a job with a custom attribute. */
public static Job generateJobWithACustomAttribute(String companyName) {
  // requisition id should be a unique Id in your system.
  String requisitionId = "jobWithACustomAttribute:" + String.valueOf(new Random().nextLong());
  ApplicationInfo applicationInfo =
      new ApplicationInfo().setUris(Arrays.asList("http://careers.google.com"));

  // Constructs custom attributes map
  Map<String, CustomAttribute> customAttributes = new HashMap<>();
  customAttributes.put(
      "someFieldName1",
      new CustomAttribute().setStringValues(Arrays.asList("value1")).setFilterable(Boolean.TRUE));
  customAttributes.put(
      "someFieldName2",
      new CustomAttribute().setLongValues(Arrays.asList(256L)).setFilterable(true));

  // Creates job with custom attributes
  Job job =
      new Job()
          .setCompanyName(companyName)
          .setRequisitionId(requisitionId)
          .setTitle("Software Engineer")
          .setApplicationInfo(applicationInfo)
          .setDescription("Design, develop, test, deploy, maintain and improve software.")
          .setCustomAttributes(customAttributes);
  System.out.println("Job generated: " + job);
  return job;
}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

def generate_job_with_custom_attributes(company_name):
    # Requisition id should be a unique Id in your system.
    requisition_id = 'job_with_custom_attributes:' + ''.join(
        random.choice(string.ascii_uppercase + string.digits)
        for _ in range(16))

    job_title = 'Software Engineer'
    application_urls = ['http://careers.google.com']
    description = ('Design, develop, test, deploy, maintain and improve '
                   'software.')

    custom_attributes = {
        'someFieldName1': {
            'string_values': ['value1'],
            'filterable': True
        },
        'someFieldName2': {
            'long_values': [256],
            'filterable': True
        }
    }

    job = {
        'company_name': company_name,
        'requisition_id': requisition_id,
        'title': job_title,
        'application_info': {'uris': application_urls},
        'description': description,
        'custom_attributes': custom_attributes
    }
    print('Job generated: %s' % job)
    return job

C#

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


public static Job GenerateJobWithCustomAttribute(string companyName)
{
    ApplicationInfo applicationInfo = new ApplicationInfo()
    {
        Uris = new List<string>
        {
            "http://careers.google.com"
        }
    };

    CustomAttribute customAttribute = new CustomAttribute();
    customAttribute.StringValues = new List<String>()
    {
        "attribute"
    };

    Dictionary<String, CustomAttribute> customAttributes = new Dictionary<string, CustomAttribute>
    {
        { "custom_attribute", customAttribute }
    };

    Job customJob = new Job()
    {
        Title = "Software Engineer",
        RequisitionId = generateRandom(),
        Description = "My Job Description Here",
        CompanyName = myCompany.Name,
        ApplicationInfo = applicationInfo,
        CustomAttributes = customAttributes
    };

    Console.WriteLine("Created custom job: " + customJob.Title);
    return customJob;
}

Go

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


// constructJobWithCustomAttributes constructs a job with custom attributes.
func constructJobWithCustomAttributes(companyName string, jobTitle string) *talent.Job {
	// requisitionID shoud be the unique ID in your system
	requisitionID := fmt.Sprintf("job-with-custom-attribute-%d", time.Now().UnixNano())

	job := &talent.Job{
		RequisitionId: requisitionID,
		Title:         jobTitle,
		CompanyName:   companyName,
		ApplicationInfo: &talent.ApplicationInfo{
			Uris: []string{"https://googlesample.com/career"},
		},
		Description: "Design, devolop, test, deploy, maintain and improve software.",
		CustomAttributes: map[string]talent.CustomAttribute{
			"someFieldString": {
				Filterable:   true,
				StringValues: []string{"someStrVal"},
			},
			"someFieldLong": {
				Filterable: true,
				LongValues: []int64{900},
			},
		},
	}
	return job
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/**
 * Generate a job with a custom attribute.
 */
const generateJobWithACustomAttribute = (companyName) => {
  const requisitionId = `jobWithACustomAttribute: ${new Date().getTime()}`;
  const jobTitle = 'Software Engineer';
  const applicationUrls = ['http://careers.google.com'];
  const description =
    'Design, develop, test, deploy, maintain and improve software.';

  const customAttributes = {
    someFieldName1: {stringValues: ['value1'], filterable: true},
    someFieldName2: {longValues: [256], filterable: true},
  };

  const job = {
    companyName: companyName,
    requisitionId: requisitionId,
    title: jobTitle,
    applicationInfo: {uris: applicationUrls},
    description: description,
    customAttributes: customAttributes,
  };

  console.log(`Job generated: ${JSON.stringify(job)}`);
  return job;
};

Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

# company_name   = "The resource name of the company listing the job. The format is "projects/{project_id}/companies/{company_id}""
# requisition_id = "The posting ID, assigned by the client to identify a job"

require "google/apis/jobs_v3"

jobs = Google::Apis::JobsV3
talent_solution_client = jobs::CloudTalentSolutionService.new
# @see
# https://developers.google.com/identity/protocols/application-default-credentials#callingruby
talent_solution_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)
# Constructs custom attributes map
custom_attributes = {}
# First custom attribute
custom_attributes["someFieldName1"] = jobs::CustomAttribute.new string_values: ["value1"],
                                                                filterable:    true
# Second custom attribute
custom_attributes["someFieldName2"] = jobs::CustomAttribute.new long_values: [256],
                                                                filterable:  true
# Creates job with custom attributes
job_generated =
  jobs::Job.new requisition_id:    requisition_id,
                title:             " Lab Technician",
                company_name:      company_name,
                application_info:  (jobs::ApplicationInfo.new uris: ["http://careers.google.com"]),
                description:       "Design, develop, test, deploy, maintain and improve software.",
                custom_attributes: custom_attributes

puts "Featured Job generated: #{job_generated.to_json}"
job_generated

Retrieve job

You can confirm that the job was created by using the GET operation to GET the details of the job. Note that it might take a couple of minutes for the job to become available, based on the current volume of jobs being created in Cloud Talent Solution.

You can retrieve the details of a previously inserted job by sending a GET request to the Cloud Talent Solution. The URI should include the previously inserted job name returned by the original create request, as a URL parameter.

The following example uses a GET operation to retrieve the details of a job with a given name:

Java

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/** Get a job. */
public static Job getJob(String jobName) throws IOException {
  try {
    Job jobExisted = talentSolutionClient.projects().jobs().get(jobName).execute();
    System.out.println("Job existed: " + jobExisted);
    return jobExisted;
  } catch (IOException e) {
    System.out.println("Got exception while getting job");
    throw e;
  }
}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

def get_job(client_service, job_name):
    try:
        job_existed = client_service.projects().jobs().get(
            name=job_name).execute()
        print('Job existed: %s' % job_existed)
        return job_existed
    except Error as e:
        print('Got exception while getting job')
        raise e

C#

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


public static Job GetJob(String jobName)
{
    try
    {
        Job jobExisted = jobServiceClient.Projects.Jobs.Get(jobName).Execute();
        Console.WriteLine("Job exists: " + jobExisted.Name);
        return jobExisted;
    }
    catch (Exception e)
    {
        Console.WriteLine("Got exception while getting job");
        throw e;
    }
}

Go

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


// getJob gets a job by name.
func getJob(w io.Writer, jobName string) (*talent.Job, error) {
	ctx := context.Background()

	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %v", err)
	}

	job, err := service.Projects.Jobs.Get(jobName).Do()
	if err != nil {
		return nil, fmt.Errorf("Failed to get job %s: %v", jobName, err)
	}

	fmt.Fprintf(w, "Job: %q", job.Name)

	return job, err
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


/**
 * Get a job.
 */
const getJob = async (jobServiceClient, jobName) => {
  try {
    const request = {
      name: jobName,
    };

    const jobExisted = await jobServiceClient.projects.jobs.get(request);

    console.log(`Job existed: ${JSON.stringify(jobExisted.data)}`);
    return jobExisted.data;
  } catch (e) {
    console.error('Got exception while getting job');
    throw e;
  }
};

Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

# job_name  = "The name of the job you want to get"
require "google/apis/jobs_v3"

jobs = Google::Apis::JobsV3

talent_solution_client = jobs::CloudTalentSolutionService.new
talent_solution_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)

begin
  job_got = talent_solution_client.get_project_job job_name
  puts "Job got: #{job_got.to_json}"
  return job_got
rescue StandardError => e
  puts "Exception occurred while getting job: #{e}"
end

Search for jobs

You've created your first company and job using the Cloud Talent Solution! You're now ready to search to conduct a search across these jobs.