Create an API Key
Since we'll be using curl to send a request to the Translation API, we'll need to generate an API key to pass in our request URL. To create an API key, navigate to APIs & services in the left menu and click on Credentials:
Then click Create credentials:
In the drop down menu, select API key:
Copy the key you just generated.
Next you'll save it to an environment variable to avoid having to insert the value of your API key in each request.
Run the following in Cloud Shell. Be sure to replace
<your_api_key>
with the key you just copied:export API_KEY=<YOUR_API_KEY>
Translate Text
In this example you will translate the string "My name is Steve" into Spanish.
Pass the text to be translated, along with the API key environment variable, to the Translation API with the following
curl
command:TEXT="My%20name%20is%20Steve"
curl "https://translation.googleapis.com/language/translate/v2?target=es&key=${API_KEY}&q=${TEXT}"
Your response should look like this:
{
"data": {
"translations": [
{
"translatedText": "Mi nombre es Steve",
"detectedSourceLanguage": "en"
}
]
}
}
In the response, you can see that the translated text and the source language that the API detected.
Detect Language
In addition to translating text, the Translation API also lets you detect the language of the text. In this example you will detect the language of two strings.
Pass the text to be examined, along with the API key environment variable, to the Translation API with the following curl command:
TEXT_ONE="Meu%20nome%20é%20Steven"
TEXT_TWO="日本のグーグルのオフィスは、東京の六本木ヒルズにあります"
curl "https://translation.googleapis.com/language/translate/v2/detect?key=${API_KEY}&q=${TEXT_ONE}&q=${TEXT_TWO}"
Your response should look like this:
{
"data": {
"detections": [
[
{
"confidence": 0.20671661198139191,
"isReliable": false,
"language": "pt"
}
],
[
{
"confidence": 0.97750955820083618,
"isReliable": false,
"language": "ja"
}
]
]
}
}
The languages returned by this sample are "pt" and "ja". These are the ISO-639-1identifiers for Portuguese and Japanese. This list of languages supported by the Translation API lists all the possible language codes which can be returned.
沒有留言:
張貼留言