Use the Cloud Client Libraries in Cloud Code

This page shows you how to get started quickly with Cloud Client Libraries and Cloud Code. You'll set up a new Kubernetes application using a Hello World sample application and then update the application to use the Cloud Translation API to translate the response to Spanish.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the Google Kubernetes Engine and Cloud Translation APIs.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the Google Kubernetes Engine and Cloud Translation APIs.

    Enable the APIs

  8. Install Git so that Cloud Code can perform Git operations, like cloning a sample.
  9. Install the Cloud Code plugin if you haven't already.

Creating an application

  1. From the command palette (Cmd/Ctrl+Shift+P), run Cloud Code: New Application, choose Kubernetes Application, and then choose a Hello World app in the language you prefer. For example, choose Node.js: Hello World to create a starter Node.js Hello World app.
  2. Save the new application. A notification confirms that your application has been created and a new window with your application opens.

Set up credentials

  1. To open a terminal, click Terminal > New Terminal.

  2. Create a service account to authenticate your API requests:

    gcloud iam service-accounts create \
    translation-quickstart \
    --project PROJECT_ID
    
  3. Grant your service account the Cloud Translation API User role:

    gcloud projects \
    add-iam-policy-binding \
    PROJECT_ID \
    --member='serviceAccount:translation-quickstart@PROJECT_ID.iam.gserviceaccount.com' \
    --role='roles/cloudtranslate.user'
    
  4. Create a service account key:

    gcloud iam service-accounts keys \
    create key.json --iam-account \
    translation-quickstart@PROJECT_ID.iam.gserviceaccount.com
    
  5. Set the key as your default credentials:

    export \
     GOOGLE_APPLICATION_CREDENTIALS=key.json
    

Call the Cloud Translation API from your application

Go

  1. Install the Cloud Translation API Cloud Client Libraries:

    1. To open a terminal, click Terminal > New Terminal.
    2. Run the following command:

      go get cloud.google.com/go/translate/apiv3
      
  2. Create an app.go file.

  3. Open app.go and add your package name, imports, and app skeleton:

    package main
    
    import (
      "context"
      "fmt"
    
      translate "cloud.google.com/go/translate/apiv3"
      translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
    )
    
    func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
    
    }
    
    func main() {
    
    }
    
  4. In your translateText() function, add the following code, which translates the specified text. Select File > Save to reformat your code:

    ctx := context.Background()
    client, err := translate.NewTranslationClient(ctx)
    if err != nil {
      return fmt.Errorf("NewTranslationClient: %v", err)
    }
    defer client.Close()
    
    req := &translatepb.TranslateTextRequest{
      Parent:             fmt.Sprintf("projects/%s/locations/global", projectID),
      SourceLanguageCode: sourceLang,
      TargetLanguageCode: targetLang,
      MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
      Contents:           []string{text},
    }
    
    resp, err := client.TranslateText(ctx, req)
    if err != nil {
      return fmt.Errorf("TranslateText: %v", err)
    }
    
    // Display the translation for each input text provided
    for _, translation := range resp.GetTranslations() {
      fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
    }
    
    return nil
    
  5. In your main() function, call translateText(). The following parameter values translate English to Spanish:

    projectID := "<var>PROJECT_ID</var>"
    sourceLang := "en-US"
    targetLang := "es"
    text := "Text to translate"
    
    err := translateText(os.Stdout, projectID, sourceLang, targetLang, text)
    if err != nil {
      fmt.Print(err)
    }
    
  6. From the terminal, run your application.

    go run app.go
    

Node.js

  1. Install the Cloud Translation API Cloud Client Libraries:

    1. Click Cloud Code and then expand the Cloud APIs explorer.
    2. Expand Cloud AI and then click Cloud Translation API.
    3. To install the client library, click NodeJS and then click play_arrow Run in terminal.
  2. Create an app.js file in your project.

  3. Openapp.js and import the Translation client library at the beginning of the file:

    const {TranslationServiceClient} = require('@google-cloud/translate');
    
  4. Create a Translation API client and add variables for your project ID, location, and the text that you want to translate:

    // Instantiates a client
    const translationClient = new TranslationServiceClient();
    
    const projectId = 'PROJECT_ID';
    const location = 'global';
    const text = 'Hello, world!';
    
  5. Add the following async function, which detects the language of your Hello, world! text and translates the text to Spanish:

    async function translateText() {
        // Construct request
        const request = {
            parent: `projects/PROJECT_ID/locations/LOCATION`,
            contents: [text],
            mimeType: 'text/plain', // mime types: text/plain, text/html
            sourceLanguageCode: 'en',
            targetLanguageCode: 'es',
        };
    
        // Run request
        const [response] = await translationClient.translateText(request);
    
        for (const translation of response.translations) {
            console.log(`Translation: ${translation.translatedText}`);
        }
    }
    
  6. At the end of your app.js file, call translateText():

    translateText();
    
  7. To run your application, open the command palette (press Ctrl/Cmd + Shift + P) and then run Cloud Code: Run on Kubernetes.

  8. After the application is deployed, view your running service by opening the URL displayed in the webview.

Python

  1. Install the Cloud Translation API Cloud Client Libraries:

    1. Click Cloud Code and then expand the Cloud APIs explorer.
    2. Expand Cloud AI and then click Cloud Translation API.
    3. To install the client library, click Python and then click play_arrow Run in terminal.
      Note: If you're using a Linux-based operating system, including Chromebook, revise the command to use pip3 instead of pip. If you're using a Mac, revise the command to use pip3 and add the --user flag.
  2. Create an app.py file in your project.

  3. In app.py, import the client library at the beginning of the file:

    from google.cloud import translate
    
  4. Add the translate_text function. This initializes a client to interact with Cloud Translation API.

    def translate_text(text="Hello, world!", project_id="PROJECT_ID"):
    
    client = translate.TranslationServiceClient()
    location = "global"
    parent = "projects/PROJECT_ID/locations/LOCATION"
    
  5. To translate text from English to Spanish and print the result, in your translate_text function, add the following call to the Cloud Translation API Cloud Client Libraries:

       response = client.translate_text(
        request={
            "parent": parent,
            "contents": [text],
            "mime_type": "text/plain",
            "source_language_code": "en-US",
            "target_language_code": "es",
        }
    )
    
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))
    
  6. At the end of app.py, call translate_text().

    translate_text()
    
  7. To run your application, open the command palette (press Ctrl/Cmd + Shift + P) and then run Cloud Code: Run on Kubernetes.

  8. After the application is deployed, view your running service by opening the URL displayed in the webview.

Cleaning up

After you stop your application, all Kubernetes resources deployed during the run are deleted automatically.

To avoid incurring charges to your account for other resources used in this quickstart, be sure to delete the project or delete the cluster you created if you want to reuse the project.

To delete the cluster:

  1. In the Kubernetes Explorer, pause on your cluster name and then click open_in_new Open in Google Cloud console.
  2. Click Delete and then click Delete.

To delete your project (and associated resources, including any clusters):

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

Get Support

To send feedback, report issues on GitHub, or ask a question on Stack Overflow.

What's next