Google Cloud Account Purchase: Google Cloud Translation API from Zero to One Configuration and Call Guide
When localizing offshore, multilingual shelves for cross-border e-commerce goods, or building a multinational customer service system,
Google Cloud Translation API
With its huge corpus accumulation, high multilingual accuracy and near-second response delay, it has become the first choice for most technical teams.
However, for developers who are first exposed to Google Cloud (GCP), its huge console, complex IAM permission system, and various authentication credentials (Service Account) often make people dizzy.
This article will discard all official documentation rhetoric
The purest programmer real-life perspective
, don't beat around the bush, hand in hand to take you to finish from
Activate services, configure permissions, generate credentials, and call the final local code.
The whole process.
1. Core Concept: Choose the API Version that's Right for Your Business
Before the formal configuration, you must understand the two core versions of Google Cloud Translation API, which determine the interface and billing method of your subsequent calls:
Cloud Translation Basic (v2): Features: Simple, straightforward, out-of-the-box. Applicable scenarios: the most common text translation, web page translation. You just throw a piece of text into the API, and it will automatically detect the language and return the translation. You can use a simple API key or service account to make calls.
Cloud Translation Advanced (v3): Features: Enterprise-class, highly customized. Application scenarios: You need to use a glossary (Glossaries)(e. g., specific brand names, industry-specific words do not want to be forcibly translated), or you need to specify custom translation models (Custom Models) for specific domains. It must use the service account (Service Account) for OAuth2 authentication.
Practical advice: If your business does not have extremely professional industry terminology requirements, it is strongly recommended to start configuration from v2 (Basic), which has the lowest development and docking cost and can fully meet more than 95% of daily translation requirements.
2. First Step: Create a Project and Enable an API Service
The foundation of all GCP operations begins with the Project (Project) ". If you don't have a Google Cloud account, please register and bind a billing credit card first (new users usually have a free amount of $300).
1. Create or select a project
Log in to the Google Cloud Console.
Click the project selection drop-down box in the upper left corner and click "New Project.
Google Cloud Account Purchase
Enter the project name (for example: my-translation-service), select your organization, and click Create.
2. Enable Translation API
In the search bar at the top of the console, enter Cloud Translation API ".
Click in the search results to go to the product page.
Make sure the project you just created is selected in the upper left corner, then click the blue Enable button. Note: If the system prompts you to bind a settlement account, please follow the prompts to complete the credit card binding, otherwise the API cannot be activated.
3. Step 2: Configure Authentication Credentials (Key Pit Avoidance)
Google Cloud strongly discourages exposing global API keys in production environments for security purposes. In order to invoke the interface, we need to generate appropriate authentication credentials. The two most common configurations are provided here.
Method A: Use API Key-suitable for v2 rapid development and testing
If you select the v2 version and only call between back-end servers, using API Key is the fastest way.
In the left-side navigation pane of the console, go to APIs & Services-> Credentials (Credentials).
Click CREATE CREDENTIALS at the top of the page and select API key.
The system will pop up a window showing a string similar to AIzaSy..., which is your API Key. Copy it and keep it safe.
⚠High Risk Warning (Required Configuration): The newly created API Key has no restrictions by default. If a hacker sweeps it and steals it, your credit card will explode instantly. Click Modify (pencil icon) to the right of the key ". In the API restrictions module, select the Restrict key. Select Cloud Translation API in the drop-down menu ". Save. In this way, even if this key is leaked, it can only be used to call the translation service and cannot be used to open a high-profile cloud server to mine.
Method B: Use a service account (Service Account)-Production environment specification (supports v2 and v3)
Google Cloud Account Purchase
For the official launch of the project, using the service account to generate the JSON credential file is the standard practice recommended by Google.
Also on the "Credentials" page, click "Create Credentials" and this time select "Service Account" (Service Account).
Enter the service account name (for example, translation-user) and click Create and Continue ".
Assign permissions (key): In the Role drop-down box, search for and select Cloud Translation -> Clou
d Translation API User (Cloud Translation API User). This role has the minimum necessary permissions to invoke the translation interface.
Click Continue and Finish.
Go back to the Credentials page, find the account you just created in the Service Account list, and click Manage keys on the right.
Click ADD KEY-> Create new key and select JSON as the type.
After clicking Create, the browser will automatically download a file called xxxx-uuid.json. This file is your private key and must not be uploaded to public platforms such as GitHub!
4. Step 3: Local Development and Code Practice (Multi-language Landing)
After getting the certificate, we can write code locally for debugging. The following are given respectively based on
API Key
The simplest HTTP request method, and based on
JSON Credentials
The production-level mainstream language SDK implementation.
1. Minimal flow: HTTP POST request using API Key
If you don't want to install any SDK, just use
curl
Or a commonly used HTTP client (such as Axios, Postman) can call the v2 interface.
Request URL:https://translation.googleapis.com/language/translate/v2
Request method: POST
Query parameter: key = your API_KEY
Request Body (JSON):
JSON
{
"q": ["Hello world! ", "How are you today?"]
"target": "zh-CN"
}
Return Results (Response):
JSON
{
"data": {
"translations ": [
{
"translatedText": "Hello, world! ",
"detectedSourceLanguage": "en"
},
{
"translatedText": "How are you today?",
"detectedSourceLanguage": "en"
}
]
}
}
2. Production flow: Use service account JSON credentials (take Node.js and Python as examples)
Using the official
Before the SDK, you need to configure an environment variable in your local running environment or server to tell the SDK where to put your JSON credentials.
Linux / macOS configuration command: Bashexport GOOGLE_APPLICATION_CREDENTIALS = "/path/to/your/google-credentials.json"
Windows (PowerShell) configuration command: PowerShell$env:GOOGLE_APPLICATION_CREDENTIALS = "C:\path\to\your\google-credentials.json"
🐍Python Code (v2)
First install the official dependency library:
Purchase a Google Cloud account
Bash
pip install google-cloud-translate==2.0.1
Write and run the script:
Python
from google.cloud import translate_v2 as translate
def translate_text(text, target_language="zh-CN"):
# The SDK automatically reads the JSON credentials in the environment variable GOOGLE_APPLICATION_CREDENTIALS
translate_client = translate.Client()
# If a list is passed in, batch translation is supported.
if isinstance(text, bytes):
text = text.decode("utf-8")
result = translate_client.translate(text, target_language=target_language)
print(f "original text: {result['input']}")
print(f "Translation result: {result['translatedText']}")
print(f "Detected source language: {result['detectedSourceLanguage']}")
if __name__ == "__main__":
translate_text("Boost your productivity with Google Cloud! ", ta
rget_language = "zh-CN")
🟢Node.js Practical Code (v2)
First, install the official dependency library:
Bash
npm install @google-cloud/translate
Write and run the code:
JavaScript
const { Translate } = require('@google-cloud/translate').v2;
// Instantiate the client. The SDK automatically looks for the credentials from the environment variables.
const translate = new Translate();
async function quickStart() {
const text = 'Hello, international expansion! ';
const target = 'zh-CN; // Target language: Simplified Chinese
try {
const [translation] = await translate.translate(text, target);
console.log('Text: ${text}');
console.log('Translation: ${translation}');
} catch (error) {
console.error ('translation error: ', error);
}
}
quickStart();
5. Cost Control and Pit-Avoidance Hardcore Guide
The Google Cloud Translation API is not free, it is billed
Charge by number of characters (Characters)
, including spaces. If it is not controlled, malicious concurrency of front-end users or endless loop calls at the code level will bring heavy economic bills to enterprises.
1. Clear the price account (take v2 price as an example)
Each billing month, Google Cloud gives away a free credit of 500000 characters (500,000 characters). Enough for a small test or a personal blog.
After exceeding the free limit, the price is $20/million characters (Million characters).
Abacus: When translating rich text containing a large number of HTML tags, the HTML tags themselves (such as <p>, <div>, class = "xxx") will also be counted as character billing. Therefore, before feeding the text into the API, it is best to strip the HTML tags at the code level and reassemble them after translating the plain text.
Can help you directly save 30% to 50% of the huge bill.
2. Configure "fuse limit" in the console"
In order to prevent sky-high bills due to code dead loops or hacking, the call cap must be locked on the first day.
In the GCP console, go to "APIs and Services"-> "Enabled APIs and Services" and find the Cloud Translation API.
After clicking Enter, switch to the Quotas & System Limits tab.
Find Queries per minute (Queries per minute) and Characters per day limit (Characters per day) ".
Click Modify to limit it to a reasonable range of your business estimate (e. g., up to 200,000 characters per day). Once exceeded, the API will directly return 429 Too Many Requests to report an error, thus deadlocking your credit card spending limit.
3. Build a local cache layer (Cache)
Translation business has a natural characteristic: high frequency words and fixed sentence repetition rate is very high.
Purchase a Google Cloud account
Architecture optimization: Build a simple cache layer on your back-end server (e. g. using Redis). Before calling the interface each time, first check Redis whether there is a translation target cache corresponding to the text (for example, MD5 (original text + target language) as the Key).
If so, read the cache directly, which takes 1 millisecond and costs 0. If not, call the Google API again and write the results back to Redis. This simple move can directly cut more than 60% of API overhead for mature applications.
6. Summary
The core context of configuring Google Cloud Translation API is actually very clear:
Build project-> start service-> take certificate (constraint authority)-> match environment change-> set limit explosion-proof card
.
For the daily overseas business of enterprises, keep in mind the "minimum permission principle" and use the service account (Service Account), and match the back-end Redis cache and the quota hard top on the GCP side, you can have a set of stable, high-throughput, and budget fully controllable top-level multilingual translation infrastructure.
