Stay organized with collections Save and categorize content based on your preferences.
Use the Cloud Client Libraries in Cloud CodeThis 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 beginIn the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Verify 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.
Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.Verify that billing is enabled for your Google Cloud project.
Enable the Google Kubernetes Engine and Cloud Translation APIs.
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.If you acquired the service account key from an external source, you must validate it before use. For more information, see Security requirements for externally sourced 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
Install the Cloud Translation API Cloud Client Libraries:
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, 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)
}
From the terminal, run your application.
go run app.go
Open pom.xml
and add the following code snippet to the dependencies
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 the dependencyManagement
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
.
Inapp.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 your App
class. This method sets and passes variables to an overloaded translateText()
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 to translateText()
:
try {
translateText();
}
catch (IOException e) {
e.printStackTrace();
}
Install the Cloud Translation API Cloud Client Libraries:
Create an app.js
file in your project.
Openapp.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 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}`); } }
At the end of your app.js
file, call translateText()
:
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.
Install the Cloud Translation API Cloud Client Libraries:
pip3
instead of pip
. If you're using a Mac, revise the command to use pip3
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
, call translate_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.
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:
To delete your project (and associated resources, including any clusters):
appspot.com
URL, delete selected resources inside the project instead of deleting the whole project.If you plan to explore multiple architectures, tutorials, or quickstarts, reusing projects can help you avoid exceeding project quota limits.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-08-07 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-08-07 UTC."],[[["This guide demonstrates how to use Cloud Client Libraries with Cloud Code to create a Kubernetes application and integrate the Cloud Translation API."],["The process involves setting up a new application, configuring credentials for API access, and using provided code examples in Go, Java, Node.js, or Python to call the Cloud Translation API."],["You will learn how to translate text from one language to another (English to Spanish, in the examples) by leveraging the Cloud Translation API's capabilities."],["The tutorial covers the steps to install the necessary client libraries, set up service accounts for authentication, and run the application on Kubernetes."],["The guide also details how to clean up resources by deleting the cluster or project after finishing, to avoid unnecessary charges."]]],[]]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4