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
- 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.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Google Kubernetes Engine and Cloud Translation APIs.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Google Kubernetes Engine and Cloud Translation APIs.
- Install Git so that Cloud Code can perform Git operations, like cloning a sample.
- Install the Cloud Code plugin if you haven't already.
Create an application
- 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. - Save the new application. A notification confirms that your application has been created and a new window with your application opens.
Set up credentials
To open a terminal, click Terminal > New Terminal.
Create a service account to authenticate your API requests:
gcloud iam service-accounts create \ translation-quickstart \ --project PROJECT_ID
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'
Create a service account key:
gcloud iam service-accounts keys \ create key.json --iam-account \ translation-quickstart@PROJECT_ID.iam.gserviceaccount.com
Set the key as your default credentials:
export \ GOOGLE_APPLICATION_CREDENTIALS=key.json
Call the Cloud Translation API from your application
Go
Install the Cloud Translation API Cloud Client Libraries:
- To open a terminal, click Terminal > New Terminal.
Run the following command:
go get cloud.google.com/go/translate/apiv3
Create an
app.go
file.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() { }
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
In your
main()
function, calltranslateText()
. 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) }
From the terminal, run your application.
go run app.go
Java
Open
pom.xml
and add the following code snippet to thedependencies
section:<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-translate</artifactId> </dependency> </dependencies>
Then, in the
pom.xml
file, add the following code snippet to thedependencyManagement
section:<dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>26.39.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
Make sure you're using the latest version of Google Cloud Supported Libraries. For a list of versions, see Google Cloud Supported Libraries.
When asked if you want to synchronize the Java classpath/configuration, click Always.
Create a file named
app.java
.In
app.java
, include the following imports after the package definition:import com.google.cloud.translate.v3.LocationName; import com.google.cloud.translate.v3.TranslateTextRequest; import com.google.cloud.translate.v3.TranslateTextResponse; import com.google.cloud.translate.v3.Translation; import com.google.cloud.translate.v3.TranslationServiceClient; import java.io.IOException;
Add the
translateText()
method to yourApp
class. This method sets and passes variables to an overloadedtranslateText()
method. The following values translate English to Spanish:public static void translateText() throws IOException { String projectId = "<walkthrough-project-id/>"; String targetLanguage = "es"; String text = "Hello world!"; translateText(projectId, targetLanguage, text); }
Add an overloaded
translateText()
method. This method takes text and translates it to the target language.public static void translateText(String projectId, String targetLanguage, String text) throws IOException { try (TranslationServiceClient client = TranslationServiceClient.create()) { LocationName parent = LocationName.of(projectId, "global"); TranslateTextRequest request = TranslateTextRequest.newBuilder() .setParent(parent.toString()) .setMimeType("text/plain") .setTargetLanguageCode(targetLanguage) .addContents(text) .build(); TranslateTextResponse response = client.translateText(request); // Display the translation for each input text provided for (Translation translation : response.getTranslationsList()) { System.out.printf("Translated text: %s\n", translation.getTranslatedText()); } } }
Replace the print statement in your
main
with a call totranslateText()
:try { translateText(); } catch (IOException e) { e.printStackTrace(); }
Node.js
Install the Cloud Translation API Cloud Client Libraries:
- Click Cloud Code and then expand the Cloud APIs explorer.
- Expand Cloud AI and then click Cloud Translation API.
- To install the client library, click NodeJS and then click
play_arrow
Run in terminal.
Create an
app.js
file in your project.Open
app.js
and import the Translation client library at the beginning of the file:const {TranslationServiceClient} = require('@google-cloud/translate');
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!';
Add the following
async
function, which detects the language of yourHello, 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}`); } }
At the end of your
app.js
file, calltranslateText()
:translateText();
To run your application, open the command palette (press
Ctrl
/Cmd
+Shift
+P
) and then run Cloud Code: Run on Kubernetes.After the application is deployed, view your running service by opening the URL displayed in the webview.
Python
Install the Cloud Translation API Cloud Client Libraries:
- Click Cloud Code and then expand the Cloud APIs explorer.
- Expand Cloud AI and then click Cloud Translation API.
- 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 usepip3
instead ofpip
. If you're using a Mac, revise the command to usepip3
and add the--user
flag.
Create an
app.py
file in your project.In
app.py
, import the client library at the beginning of the file:from google.cloud import translate
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"
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))
At the end of
app.py
, calltranslate_text()
.translate_text()
To run your application, open the command palette (press
Ctrl
/Cmd
+Shift
+P
) and then run Cloud Code: Run on Kubernetes.After the application is deployed, view your running service by opening the URL displayed in the webview.
Clean 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:
- In the Kubernetes Explorer, pause on your cluster name and then click open_in_new Open in Google Cloud console.
- Click Delete and then click Delete.
To delete your project (and associated resources, including any clusters):
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- 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
- Learn more about the Cloud Translation API
- Learn more about the Cloud Client Libraries
- Learn more about Cloud Code for VS Code