Crea società e offerta di lavoro

Questo tutorial è progettato per aiutarti a iniziare a esplorare e sviluppare applicazioni con Cloud Talent Solution. Si presume che tu abbia familiarità con la programmazione di base, anche se dovresti essere in grado di seguire anche senza molte conoscenze di programmazione. Dopo aver completato questo tutorial, dovresti essere in grado di utilizzare la documentazione di riferimento di Cloud Talent Solution per creare le tue applicazioni di base.

Questo tutorial illustra un'applicazione Cloud Talent Solution utilizzando il codice Java. Lo scopo di questo tutorial non è spiegare le librerie client Java, ma come effettuare chiamate a Cloud Talent Solution. Le applicazioni in Python e Node.js sono essenzialmente simili. Per eventuali domande, non esitare a contattarci.

Prima di iniziare

Sei ora in grado di eseguire le seguenti attività:

Crea un'azienda con offerte di lavoro e cerca queste offerte

Questo tutorial illustra un'applicazione Cloud Talent Solution di base e ti guida nella creazione di un singolo lavoro che associ a un'azienda. Il tutorial successivo illustra i passaggi per cercare lavoro all'interno dell'azienda in base agli attributi dei lavori e alla query di ricerca. L'API search tenta di restituire i lavori più pertinenti alla query di un candidato in base ai campi disponibili all'interno di un lavoro (nome dell'azienda, titolo del lavoro, descrizione del lavoro, categorie di lavoro, sede di lavoro, ecc.).

Crea un servizio con le tue credenziali

Crea il servizio con il file delle credenziali JSON che hai scaricato in Prima di iniziare:

Java

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


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

Python

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

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()

Go

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


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

Questo codice configura il servizio client con le informazioni sulle credenziali della tua applicazione. La richiesta OAuth 2.0 viene inviata quando viene effettuata una chiamata API. Il token di autenticazione generato utilizzando la procedura descritta sopra ha in genere una data di scadenza di 1 ora, dopodiché riceverai un errore se provi a utilizzarlo. La libreria GoogleCredential si occupa di "aggiornare" automaticamente il token, ovvero di ottenere un nuovo token di accesso.

Crea società

Un'azienda è un'entità associata a un insieme di offerte di lavoro. Devi creare l'azienda prima di poter pubblicare offerte di lavoro su Cloud Talent Solution per quell'azienda. Puoi inviare qualsiasi stringa in formato libero come externalId durante la creazione dell'azienda. Ciò significa che puoi utilizzare la chiave primaria del database esistente (se ne hai uno) quando crei un'azienda e fai riferimento a essa.

Java

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


/** 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

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

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

Go

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


// 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: %w", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %w", 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: %w", companyToCreate.DisplayName, err)
	}

	return company, nil
}

Ottieni società

Puoi leggere lo stato attuale di un'azienda inviando una richiesta GET insieme all'name dell'azienda assegnato dal nostro backend.

Java

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


/** 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

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

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

Go

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


// 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: %w", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %w", err)
	}

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

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

	return company, nil
}

Crea job

Per pubblicare un nuovo annuncio di lavoro, devi fornire tutti i campi obbligatori relativi al nuovo lavoro insieme all'companyName dell'azienda a cui vuoi associare questo lavoro, che hai specificato quando hai creato la risorsa aziendale.

L'oggetto dati con i dati del job compilati viene inviato all'endpoint Cloud Talent Solution utilizzando una richiesta POST. Tieni presente che il campo name non deve essere impostato nella richiesta iniziale, in quanto è un campo "solo output" dell'API createJob e fa parte della risposta API quando viene creata una nuova entità job dal server. L'endpoint API per interagire con la risorsa dei job è specificato nel documento delle librerie client di Cloud Talent Solution.

La risposta alla richiesta è un oggetto della nuova offerta di lavoro; deve includere un name che rappresenta in modo univoco l'offerta. Il job name viene utilizzato quando l'offerta deve essere aggiornata o eliminata. Come best practice, memorizza questo name e mappalo al tuo ID univoco per il job.

Il server restituisce un errore se tenti di inserire un job quando ne esiste già un altro nel sistema con lo stesso companyName, requisitionId e languageCode per la stessa azienda.

Il seguente codice crea un job con solo i campi obbligatori per l'azienda specificata nel campo companyName.

Java

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

/** 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

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

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

Go

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


// 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: %w", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %w", 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: %w", jobToCreate.RequisitionId, err)
	}
	return job, err
}

Cloud Talent Solution ti consente anche di creare offerte di lavoro specifiche per una località. Per saperne di più, consulta locations.

Cloud Talent Solution ha diversi campi associati a un job integrati nello schema API. Tuttavia, potresti avere ancora alcuni campi che non fanno parte dei campi predefiniti. Sebbene sia consigliabile che tutti i clienti di Cloud Talent Solution utilizzino sempre i campi predefiniti ove possibile, Cloud Talent Solution fornisce anche alcuni customAttributes per un job. Questi potrebbero essere filtrabili o non filtrabili. Per saperne di più, consulta customAttributes.

Il seguente esempio di codice mostra come creare un job con un customAttribute:

Java

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


/** Generate a job with a custom attribute. */
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
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

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

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

Go

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


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

Recupera job

Puoi verificare che il job sia stato creato utilizzando l'operazione GET per ottenere i dettagli del job. Tieni presente che potrebbero essere necessari alcuni minuti prima che il job diventi disponibile, in base al volume attuale di job creati in Cloud Talent Solution.

Puoi recuperare i dettagli di un job inserito in precedenza inviando una richiesta GET a Cloud Talent Solution. L'URI deve includere il job name inserito in precedenza e restituito dalla richiesta di creazione originale come parametro URL.

L'esempio seguente utilizza un'operazione GET per recuperare i dettagli di un job con un determinato name:

Java

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

/** 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

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.

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

Go

Per saperne di più sull'installazione e la creazione di un client Cloud Talent Solution, consulta Librerie client Cloud Talent Solution.


// 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: %w", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %w", err)
	}

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

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

	return job, err
}

Ricerca lavoro

Hai creato la tua prima azienda e il tuo primo lavoro utilizzando Cloud Talent Solution. Ora puoi cercare per eseguire una ricerca tra questi lavori.

Passaggi successivi

  • Scopri di più sulle aziende.
  • Scopri di più sui job.