Discovering supported languages (Advanced)

This document describes how to use the Cloud Translation API to list supported languages using Cloud Translation - Advanced.

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/v3/projects/project-number-or-id/locations/location/supportedLanguages

Get 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/v3/projects/project-number-or-id/locations/location/supportedLanguages URL. 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.

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your Google Cloud project number or ID

HTTP method and URL:

GET https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages

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/v3/projects/project-number-or-id/locations/global/supportedLanguages

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/v3/projects/project-number-or-id/locations/global/supportedLanguages " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "languages": [
     "languageCode": "af",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "ar",
      "supportSource": true,
      "supportTarget": true
    },
    ....
    {
      "languageCode": "zu",
      "supportSource": true,
      "supportTarget": true
    }
   ]
}

The list is sorted alphabetically by language code. 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. For example:

   {
      "languageCode": "zh-TW",
      "supportSource": true,
      "supportTarget": true
    },

C#

Before trying this sample, follow the C# setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation C# API reference documentation.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class GetSupportedLanguages
    {
        /// <summary>
        /// Getting a list of supported language codes
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        public static void GetSupportedLanguagesSample(string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
            };
            SupportedLanguages response = translationServiceClient.GetSupportedLanguages(request);
            // List language codes of supported languages
            foreach (SupportedLanguage language in response.Languages)
            {
                Console.WriteLine($"Language Code: {language.LanguageCode}");
            }
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// getSupportedLanguages gets a list of supported language codes.
func getSupportedLanguages(w io.Writer, projectID string) error {
	// projectID := "my-project-id"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent: fmt.Sprintf("projects/%s/locations/global", projectID),
	}

	resp, err := client.GetSupportedLanguages(ctx, req)
	if err != nil {
		return fmt.Errorf("GetSupportedLanguages: %v", err)
	}

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
	}

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Java API reference documentation.

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguages {

  public static void getSupportedLanguages() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    getSupportedLanguages(projectId);
  }

  // Getting a list of supported language codes
  public static void getSupportedLanguages(String projectId) throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "global");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder().setParent(parent.toString()).build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
      }
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Node.js API reference documentation.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
  };

  try {
    // Get supported languages
    const [response] = await translationClient.getSupportedLanguages(request);

    for (const language of response.languages) {
      // Supported language code, generally consisting of its ISO 639-1 identifier, for
      // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
      // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
      console.log(`Language - Language Code: ${language.languageCode}`);
      // Human readable name of the language localized in the display language specified
      // in the request.
      console.log(`Language - Display Name: ${language.displayName}`);
      // Can be used as source language.
      console.log(`Language - Support Source: ${language.supportSource}`);
      // Can be used as target language.
      console.log(`Language - Support Target: ${language.supportTarget}`);
    }
  } catch (error) {
    console.error(error.details);
  }
}

getSupportedLanguages();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation PHP API reference documentation.

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $projectId = '[Google Cloud Project ID]';
$formattedParent = $translationServiceClient->locationName($projectId, 'global');

try {
    $response = $translationServiceClient->getSupportedLanguages($formattedParent);
    // List language codes of supported languages
    foreach ($response->getLanguages() as $language) {
        printf('Language Code: %s' . PHP_EOL, $language->getLanguageCode());
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Python API reference documentation.

from google.cloud import translate


def get_supported_languages(project_id="YOUR_PROJECT_ID"):
    """Getting a list of supported language codes."""

    client = translate.TranslationServiceClient()

    parent = client.location_path(project_id, "global")

    # Supported language codes: https://cloud.google.com/translate/docs/languages
    response = client.get_supported_languages(parent=parent)

    # List language codes of supported languages.
    print("Supported Languages:")
    for language in response.languages:
        print(u"Language Code: {}".format(language.language_code))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Ruby API reference documentation.

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"

client = Google::Cloud::Translate.translation_service

parent = client.location_path project: project_id, location: location_id

response = client.get_supported_languages parent: parent

# List language codes of supported languages
response.languages.each do |language|
  puts "Language Code: #{language.language_code}"
end

Listing supported languages with target language name

REST & CMD LINE

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

Before using any of the request data below, make the following replacements:

  • project-number-or-id: your Google Cloud project number or ID

HTTP method and URL:

GET https://translation.googleapis.com/v3/projects/project-number-or-id/locations/global/supportedLanguages?display_language_code=sq

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/v3/projects/project-number-or-id/locations/global/supportedLanguages?display_language_code=sq

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/v3/projects/project-number-or-id/locations/global/supportedLanguages?display_language_code=sq " | Select-Object -Expand Content

You should receive a JSON response similar to the following:

{
  "languages": [{
      "languageCode": "af",
      "displayName": "Afrikanisht",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "am",
      "displayName": "Amarikisht",
      "supportSource": true,
      "supportTarget": true
    },
    {
      "languageCode": "en",
      "displayName": "Anglisht",
      "supportSource": true,
      "supportTarget": true
    },
    ...{
      "languageCode": "zu",
      "displayName": "Zulu",
      "supportSource": true,
      "supportTarget": true
    }

	]
}

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. In this example, the language is Albanian (sq).

C#

Before trying this sample, follow the C# setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation C# API reference documentation.


using Google.Api.Gax.ResourceNames;
using Google.Cloud.Translate.V3;
using System;

namespace GoogleCloudSamples
{
    public static class GetSupportedLanguagesForTarget
    {
        /// <summary>
        /// Listing supported languages with target language code.
        /// </summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="languageCode">Target Language Code.</param>
        public static void GetSupportedLanguagesForTargetSample(string languageCode = "en",
            string projectId = "[Google Cloud Project ID]")
        {
            TranslationServiceClient translationServiceClient = TranslationServiceClient.Create();
            GetSupportedLanguagesRequest request = new GetSupportedLanguagesRequest
            {
                ParentAsLocationName = new LocationName(projectId, "global"),
                DisplayLanguageCode = languageCode,
            };
            SupportedLanguages response = translationServiceClient.GetSupportedLanguages(request);
            // List language codes of supported languages
            foreach (SupportedLanguage language in response.Languages)
            {
                Console.WriteLine($"Language Code: {language.LanguageCode}");
                Console.WriteLine($"Display Name: {language.DisplayName}");
            }
        }
    }

Go

Before trying this sample, follow the Go setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Go API reference documentation.

import (
	"context"
	"fmt"
	"io"

	translate "cloud.google.com/go/translate/apiv3"
	translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
)

// getSupportedLanguagesForTarget gets a list of supported language codes with target language names.
func getSupportedLanguagesForTarget(w io.Writer, projectID string, languageCode string) error {
	// projectID := "my-project-id"
	// languageCode := "is"

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

	req := &translatepb.GetSupportedLanguagesRequest{
		Parent:              fmt.Sprintf("projects/%s/locations/global", projectID),
		DisplayLanguageCode: languageCode,
	}

	resp, err := client.GetSupportedLanguages(ctx, req)
	if err != nil {
		return fmt.Errorf("GetSupportedLanguages: %v", err)
	}

	// List language codes of supported languages
	fmt.Fprintf(w, "Supported languages:\n")
	for _, language := range resp.GetLanguages() {
		fmt.Fprintf(w, "Language code: %v\n", language.GetLanguageCode())
		fmt.Fprintf(w, "Display name: %v\n", language.GetDisplayName())
	}

	return nil
}

Java

Before trying this sample, follow the Java setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Java API reference documentation.

import com.google.cloud.translate.v3.GetSupportedLanguagesRequest;
import com.google.cloud.translate.v3.LocationName;
import com.google.cloud.translate.v3.SupportedLanguage;
import com.google.cloud.translate.v3.SupportedLanguages;
import com.google.cloud.translate.v3.TranslationServiceClient;
import java.io.IOException;

public class GetSupportedLanguagesForTarget {

  public static void getSupportedLanguagesForTarget() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "YOUR-PROJECT-ID";
    // Supported Languages: https://cloud.google.com/translate/docs/languages
    String languageCode = "your-language-code";
    getSupportedLanguagesForTarget(projectId, languageCode);
  }

  // Listing supported languages with target language name
  public static void getSupportedLanguagesForTarget(String projectId, String languageCode)
      throws IOException {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (TranslationServiceClient client = TranslationServiceClient.create()) {
      // Supported Locations: `global`, [glossary location], or [model location]
      // Glossaries must be hosted in `us-central1`
      // Custom Models must use the same location as your model. (us-central1)
      LocationName parent = LocationName.of(projectId, "global");
      GetSupportedLanguagesRequest request =
          GetSupportedLanguagesRequest.newBuilder()
              .setParent(parent.toString())
              .setDisplayLanguageCode(languageCode)
              .build();

      SupportedLanguages response = client.getSupportedLanguages(request);

      // List language codes of supported languages
      for (SupportedLanguage language : response.getLanguagesList()) {
        System.out.printf("Language Code: %s\n", language.getLanguageCode());
        System.out.printf("Display Name: %s\n", language.getDisplayName());
      }
    }
  }
}

Node.js

Before trying this sample, follow the Node.js setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Node.js API reference documentation.

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const projectId = 'YOUR_PROJECT_ID';
// const location = 'global';

// Imports the Google Cloud Translation library
const {TranslationServiceClient} = require('@google-cloud/translate');

// Instantiates a client
const translationClient = new TranslationServiceClient();

async function getSupportedLanguages() {
  // Construct request
  const request = {
    parent: `projects/${projectId}/locations/${location}`,
    displayLanguageCode: 'en',
  };

  try {
    // Get supported languages
    const [response] = await translationClient.getSupportedLanguages(request);

    for (const language of response.languages) {
      // Supported language code, generally consisting of its ISO 639-1 identifier, for
      // example, 'en', 'ja'. In certain cases, BCP-47 codes including language and
      // region identifiers are returned (for example, 'zh-TW' and 'zh-CN')
      console.log(`Language - Language Code: ${language.languageCode}`);
      // Human readable name of the language localized in the display language specified
      // in the request.
      console.log(`Language - Display Name: ${language.displayName}`);
      // Can be used as source language.
      console.log(`Language - Support Source: ${language.supportSource}`);
      // Can be used as target language.
      console.log(`Language - Support Target: ${language.supportTarget}`);
    }
  } catch (error) {
    console.error(error.details);
  }
}

getSupportedLanguages();

PHP

Before trying this sample, follow the PHP setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation PHP API reference documentation.

use Google\Cloud\Translate\V3\TranslationServiceClient;

$translationServiceClient = new TranslationServiceClient();

/** Uncomment and populate these variables in your code */
// $languageCode = 'en';
// $projectId = '[Google Cloud Project ID]';
$formattedParent = $translationServiceClient->locationName($projectId, 'global');

try {
    $response = $translationServiceClient->getSupportedLanguages(
        $formattedParent,
        ['displayLanguageCode' => $languageCode]
    );
    // List language codes of supported languages
    foreach ($response->getLanguages() as $language) {
        printf('Language Code: %s' . PHP_EOL, $language->getLanguageCode());
        printf('Display Name: %s' . PHP_EOL, $language->getDisplayName());
    }
} finally {
    $translationServiceClient->close();
}

Python

Before trying this sample, follow the Python setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Python API reference documentation.

from google.cloud import translate


def sample_get_supported_languages_with_target(language_code, project_id):
    """
    Listing supported languages with target language name

    Args:
      language_code The language to use to return localized,
      human readable names of supported languages.
    """

    client = translate.TranslationServiceClient()

    # TODO(developer): Uncomment and set the following variables
    # language_code = 'en'
    # project_id = '[Google Cloud Project ID]'
    parent = client.location_path(project_id, "global")

    response = client.get_supported_languages(
        display_language_code=language_code, parent=parent
    )
    # List language codes of supported languages
    for language in response.languages:
        print(u"Language Code: {}".format(language.language_code))
        print(u"Display Name: {}".format(language.display_name))

Ruby

Before trying this sample, follow the Ruby setup instructions in the Translation Quickstart Using Client Libraries. For more information, see the Translation Ruby API reference documentation.

require "google/cloud/translate"

# project_id = "[Google Cloud Project ID]"
# location_id = "[LOCATION ID]"

client = Google::Cloud::Translate.translation_service

language_code = "en"
parent = client.location_path project: project_id, location: location_id

response = client.get_supported_languages parent:                parent,
                                          display_language_code: language_code

# List language codes of supported languages
response.languages.each do |language|
  puts "Language Code: #{language.language_code}"
  puts "Display Name: #{language.display_name}"
end