Discovering supported languages (Basic)

This document describes how to use the Cloud Translation API (v2) to list supported languages.

Before you begin

Before you can start using the Cloud Translation API, you must have a project that has the Cloud Translation API enabled and the appropriate credentials. You can also install client libraries for common programming languages to help you make calls to the API.

For more information, see the Setup page.

Sending a supported languages request

You can discover the supported languages of this API by sending an HTTP request using a URL of the following format:

https://translation.googleapis.com/language/translate/v2/languages

Getting a list of supported languages

REST & CMD LINE

To get a list of all supported languages, make a GET request to the https://translation.googleapis.com/language/translate/v2/languages endpoint. The following shows an example of a GET request using curl and PowerShell. The example uses the access token for a service account set up for the project using the Google Cloud Cloud SDK. For instructions on installing the Cloud SDK, setting up a project with a service account, and obtaining an access token, see the Setup page.

HTTP method and URL:

GET https://translation.googleapis.com/language/translate/v2/languages

To send your request, choose one of these options:

curl

Execute the following command:

curl -X GET \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://translation.googleapis.com/language/translate/v2/languages

PowerShell

Execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://translation.googleapis.com/language/translate/v2/languages " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "languages": [
    {
      "language": "en"
    },
    {
      "language": "fr"
    },
    {
      "language": "zh-CN"
    }
  ]
}

This query returns ISO-639-1 language codes for supported languages. Some language codes also include a country code, like zh-CN or zh-TW. The list is sorted alphabetically by language code. The above example has been shortened due to space constraints.

C#


using Google.Cloud.Translation.V2;
using System;
using System.Collections.Generic;

public partial class TranslateSample
{
    public IList<Language> ListLanguageCodes()
    {
        TranslationClient client = TranslationClient.Create();
        IList<Language> response = client.ListLanguages();
        foreach (var language in response)
        {
            Console.WriteLine(language.Code);
        }
        return response;
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

func listSupportedLanguages(w io.Writer, targetLanguage string) error {
	// targetLanguage := "th"
	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return fmt.Errorf("language.Parse: %v", err)
	}

	client, err := translate.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("translate.NewClient: %v", err)
	}
	defer client.Close()

	langs, err := client.SupportedLanguages(ctx, lang)
	if err != nil {
		return fmt.Errorf("SupportedLanguages: %v", err)
	}

	for _, lang := range langs {
		fmt.Fprintf(w, "%q: %s\n", lang.Tag, lang.Name)
	}

	return nil
}

Java

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

List<Language> languages = translate.listSupportedLanguages();

for (Language language : languages) {
  System.out.printf("Name: %s, Code: %s\n", language.getName(), language.getCode());
}

Node.js

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

async function listLanguages() {
  // Lists available translation language with their names in English (the default).
  const [languages] = await translate.getLanguages();

  console.log('Languages:');
  languages.forEach(language => console.log(language));
}

listLanguages();

PHP

use Google\Cloud\Translate\TranslateClient;

$translate = new TranslateClient();
foreach ($translate->languages() as $code) {
    print("$code\n");
}

Python

"""Lists all available languages."""
from google.cloud import translate_v2 as translate
translate_client = translate.Client()

results = translate_client.get_languages()

for language in results:
    print(u'{name} ({language})'.format(**language))

Ruby

# project_id = "Your Google Cloud project ID"

require "google/cloud/translate"

translate = Google::Cloud::Translate.translation_v2_service project_id: project_id
languages = translate.languages

puts "Supported language codes:"
languages.each do |language|
  puts language.code
end

Listing supported languages in target language

REST & CMD LINE

Here is another example that returns the list of supported languages. The returned language names are written in a specified target language. The returned list is sorted alphabetically according to the target language.

To list supported languages in a target language, make a POST request and provide JSON that identifies the target language in the request body. The following shows an example of a POST request using curl or PowerShell.

HTTP method and URL:

POST https://translation.googleapis.com/language/translate/v2/languages

Request JSON body:

{
    "target": "zh-TW"
}

To send your request, choose one of these options:

curl

Save the request body in a file called request.json, and execute the following command:

curl -X POST \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
https://translation.googleapis.com/language/translate/v2/languages

PowerShell

Save the request body in a file called request.json, and execute the following command:

$cred = gcloud auth application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://translation.googleapis.com/language/translate/v2/languages " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "data": {
    "languages": [
      {
        "language": "zh-CN",
        "name": "中文(簡體)"
      },
      {
        "language": "fr",
        "name": "法文"
      },
      {
        "language": "en",
        "name": "英文"
      }
    ]
  }
}

In this case, the query returns the same language codes as above, along with name strings that give the names of the languages written in the target language, zh-TW. The above example has been shortened due to space constraints.

C#


using Google.Cloud.Translation.V2;
using System;
using System.Collections.Generic;

public partial class TranslateSample
{
    public IList<Language> ListLanguageNames()
    {
        TranslationClient client = TranslationClient.Create();
        // List all the languages in English.
        IList<Language> languages = client.ListLanguages(target: "en");
        foreach (var language in languages)
        {
            Console.WriteLine($"{language.Code}\t{language.Name}");
        }
        return languages;
    }
}

Go

import (
	"context"
	"fmt"
	"io"

	"cloud.google.com/go/translate"
	"golang.org/x/text/language"
)

func listSupportedLanguages(w io.Writer, targetLanguage string) error {
	// targetLanguage := "th"
	ctx := context.Background()

	lang, err := language.Parse(targetLanguage)
	if err != nil {
		return fmt.Errorf("language.Parse: %v", err)
	}

	client, err := translate.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("translate.NewClient: %v", err)
	}
	defer client.Close()

	langs, err := client.SupportedLanguages(ctx, lang)
	if err != nil {
		return fmt.Errorf("SupportedLanguages: %v", err)
	}

	for _, lang := range langs {
		fmt.Fprintf(w, "%q: %s\n", lang.Tag, lang.Name)
	}

	return nil
}

Java

// TODO(developer): Uncomment these lines.
// import com.google.cloud.translate.*;
// Translate translate = TranslateOptions.getDefaultInstance().getService();

List<Language> languages =
    translate.listSupportedLanguages(Translate.LanguageListOption.targetLanguage("es"));

for (Language language : languages) {
  System.out.printf("Name: %s, Code: %s\n", language.getName(), language.getCode());
}

Node.js

// Imports the Google Cloud client library
const {Translate} = require('@google-cloud/translate').v2;

// Creates a client
const translate = new Translate();

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const target = 'The target language for language names, e.g. ru';

async function listLanguagesWithTarget() {
  // Lists available translation language with their names in a target language
  const [languages] = await translate.getLanguages(target);

  console.log('Languages:');
  languages.forEach(language => console.log(language));
}

listLanguagesWithTarget();

PHP

use Google\Cloud\Translate\TranslateClient;

/** Uncomment and populate these variables in your code */
// $targetLanguage = 'en'; // Language to print the language names in

$translate = new TranslateClient();
$result = $translate->localizedLanguages([
    'target' => $targetLanguage,
]);
foreach ($result as $lang) {
    printf('%s: %s' . PHP_EOL, $lang['code'], $lang['name']);
}

Python

"""Lists all available languages and localizes them to the target language.

Target must be an ISO 639-1 language code.
See https://g.co/cloud/translate/v2/translate-reference#supported_languages
"""
from google.cloud import translate_v2 as translate
translate_client = translate.Client()

results = translate_client.get_languages(target_language=target)

for language in results:
    print(u'{name} ({language})'.format(**language))

Ruby

# project_id = "Your Google Cloud project ID"

# To receive the names of the supported languages, provide the code
# for the language in which you wish to receive the names
# language_code = "en"

require "google/cloud/translate"

translate = Google::Cloud::Translate.translation_v2_service project_id: project_id
languages = translate.languages language_code

puts "Supported languages:"
languages.each do |language|
  puts "#{language.code} #{language.name}"
end