Quickstart: Use the Translator Text API to get a list of supported languages

In this quickstart, you get a list of languages supported for translation, transliteration, and dictionary lookup using the Translator Text API.

Prerequisites

Create a .NET Core project

Open a new command prompt (or terminal session) and run these commands:

dotnet new console -o languages-sample
cd languages-sample

The first command does two things. It creates a new .NET console application, and creates a directory named languages-sample. The second command changes to the directory for your project.

Next, you'll need to install Json.Net. From your project's directory, run:

dotnet add package Newtonsoft.Json --version 11.0.2

Add required namespaces to your project

The dotnet new console command that you ran earlier created a project, including Program.cs. This file is where you'll put your application code. Open Program.cs, and replace the existing using statements. These statements ensure that you have access to all the types required to build and run the sample app.

using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;

Create a function to get a list of languages

Within the Program class, create a function called GetLanguages. This class encapsulates the code used to call the Languages resource and prints the result to console.

static void GetLanguages()
{
  /*
   * The code for your call to the translation service will be added to this
   * function in the next few sections.
   */
}

Set the host name, and path

Add these lines to the GetLanguages function.

string host = "https://api.cognitive.microsofttranslator.com";
string route = "/languages?api-version=3.0";

Instantiate the client and make a request

These lines instantiate the HttpClient and the HttpRequestMessage:

using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
  // In the next few sections you'll add code to construct the request.
}

Construct the request and print the response

Inside the HttpRequestMessage you'll:

  • Declare the HTTP method
  • Construct the request URI
  • Add required headers
  • Make an asynchronous request
  • Print the response

Add this code to the HttpRequestMessage:

// Set the method to GET
request.Method = HttpMethod.Get;
// Construct the full URI
request.RequestUri = new Uri(host + route);
// Send request, get response
var response = client.SendAsync(request).Result;
var jsonResponse = response.Content.ReadAsStringAsync().Result;
// Pretty print the response
Console.WriteLine(PrettyPrint(jsonResponse));
Console.WriteLine("Press any key to continue.");

If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. Learn more about authenticating with the multi-service subscription.

To print the response with "Pretty Print" (formatting for the response), add this function to your Program class:

static string PrettyPrint(string s)
{
    return JsonConvert.SerializeObject(JsonConvert.DeserializeObject(s), Formatting.Indented);
}

Put it all together

The last step is to call GetLanguages() in the Main function. Locate static void Main(string[] args) and add these lines:

GetLanguages();
Console.ReadLine();

Run the sample app

That's it, you're ready to run your sample app. From the command line (or terminal session), navigate to your project directory and run:

dotnet run

Sample response

Find the country/region abbreviation in this list of languages.

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

Clean up resources

Make sure to remove any confidential information from your sample app's source code, like subscription keys.

Next steps

Take a look at the API reference to understand everything you can do with the Translator Text API.

Prerequisites

Initialize a project with Gradle

Let's start by creating a working directory for this project. From the command line (or terminal), run this command:

mkdir get-languages-sample
cd get-languages-sample

Next, you're going to initialize a Gradle project. This command will create essential build files for Gradle, most importantly, the build.gradle.kts, which is used at runtime to create and configure your application. Run this command from your working directory:

gradle init --type basic

When prompted to choose a DSL, select Kotlin.

Configure the build file

Locate build.gradle.kts and open it with your favorite IDE or text editor. Then copy in this build configuration:

plugins {
    java
    application
}
application {
    mainClassName = "GetLanguages"
}
repositories {
    mavenCentral()
}
dependencies {
    compile("com.squareup.okhttp:okhttp:2.5.0")
    compile("com.google.code.gson:gson:2.8.5")
}

Take note that this sample has dependencies on OkHttp for HTTP requests, and Gson to handle and parse JSON. If you'd like to learn more about build configurations, see Creating New Gradle Builds.

Create a Java file

Let's create a folder for your sample app. From your working directory, run:

mkdir -p src/main/java

Next, in this folder, create a file named GetLanguages.java.

Import required libraries

Open GetLanguages.java and add these import statements:

import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;

Define variables

First, you'll need to create a public class for your project:

public class GetLanguages {
  // All project code goes here...
}

Add these lines to the GetLanguages class:

String url = "https://api.cognitive.microsofttranslator.com/languages?api-version=3.0";

If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. Learn more about authenticating with the multi-service subscription.

Create a client and build a request

Add this line to the GetLanguages class to instantiate the OkHttpClient:

// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();

Next, let's build the GET request.

// This function performs a GET request.
public String Get() throws IOException {
    Request request = new Request.Builder()
            .url(url).get()
            .addHeader("Content-type", "application/json").build();
    Response response = client.newCall(request).execute();
    return response.body().string();
}

Create a function to parse the response

This simple function parses and prettifies the JSON response from the Translator Text service.

// This function prettifies the json response.
public static String prettify(String json_text) {
    JsonParser parser = new JsonParser();
    JsonElement json = parser.parse(json_text);
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    return gson.toJson(json);
}

Put it all together

The last step is to make a request and get a response. Add these lines to your project:

public static void main(String[] args) {
    try {
        GetLanguages getLanguagesRequest = new GetLanguages();
        String response = getLanguagesRequest.Get();
        System.out.println(prettify(response));
    } catch (Exception e) {
        System.out.println(e);
    }
}

Run the sample app

That's it, you're ready to run your sample app. From the command line (or terminal session), navigate to the root of your working directory and run:

gradle build

When the build completes, run:

gradle run

Sample response

Find the country/region abbreviation in this list of languages.

A successful response is returned in JSON as shown in the following example:

{
  "translation": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr"
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl"
    },
...
  },
  "transliteration": {
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "scripts": [
        {
          "code": "Arab",
          "name": "Arabic",
          "nativeName": "العربية",
          "dir": "rtl",
          "toScripts": [
            {
              "code": "Latn",
              "name": "Latin",
              "nativeName": "اللاتينية",
              "dir": "ltr"
            }
          ]
        },
        {
          "code": "Latn",
          "name": "Latin",
          "nativeName": "اللاتينية",
          "dir": "ltr",
          "toScripts": [
            {
              "code": "Arab",
              "name": "Arabic",
              "nativeName": "العربية",
              "dir": "rtl"
            }
          ]
        }
      ]
    },
...
  },
  "dictionary": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
...
  }
}

Next steps

Take a look at the API reference to understand everything you can do with the Translator Text API.

Prerequisites

This quickstart requires:

  • Python 2.7.x or 3.x

Create a project and import required modules

Create a new Python project using your favorite IDE or editor. Then copy this code snippet into your project in a file named get-languages.py.

# -*- coding: utf-8 -*-
import os
import requests
import uuid
import json

Note

If you haven't used these modules you'll need to install them before running your program. To install these packages, run: pip install requests uuid.

The first comment tells your Python interpreter to use UTF-8 encoding. Then required modules are imported to read your subscription key from an environment variable, construct the http request, create a unique identifier, and handle the JSON response returned by the Translator Text API.

Set the base url, and path

The Translator Text global endpoint is set as the base_url. path sets the languages route and identifies that we want to hit version 3 of the API.

Note

For more information about endpoints, routes, and request parameters, see Translator Text API 3.0: Languages.

base_url = 'https://api.cognitive.microsofttranslator.com'
path = '/languages?api-version=3.0'
constructed_url = base_url + path

Add headers

The request to get supported languages doesn't require authentication. Set the Content-type as application/json and add X-ClientTraceId to uniquely identify your request.

Copy this code snippet into your project:

headers = {
    'Content-type': 'application/json',
    'X-ClientTraceId': str(uuid.uuid4())
}

If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. Learn more about authenticating with the multi-service subscription.

Create a request to get a list of supported languages

Let's create a GET request using the requests module. It takes two arguments: the concatenated URL, and the request headers:

request = requests.get(constructed_url, headers=headers)
response = request.json()

The last step is to print the results. This code snippet prettifies the results by sorting the keys, setting indentation, and declaring item and key separators.

print(json.dumps(response, sort_keys=True, indent=4,
                 ensure_ascii=False, separators=(',', ': ')))

Put it all together

That's it, you've put together a simple program that will call the Translator Text API and return a JSON response. Now it's time to run your program:

python get-languages.py

If you'd like to compare your code against ours, the complete sample is available on GitHub.

Sample response

Find the country/region abbreviation in this list of languages.

This sample has been truncated to show a snippet of the result:

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

Clean up resources

If you've hardcoded your subscription key into your program, make sure to remove the subscription key when you're finished with this quickstart.

Next steps

Take a look at the API reference to understand everything you can do with the Translator Text API.

Prerequisites

This quickstart requires:

Create a project and import required modules

Create a new project using your favorite IDE or editor. Then copy this code snippet into your project in a file named get-languages.js.

const request = require('request');
const uuidv4 = require('uuid/v4');

Note

If you haven't used these modules you'll need to install them before running your program. To install these packages, run: npm install request uuidv4.

These modules are required to construct the HTTP request, and create a unique identifier for the 'X-ClientTraceId' header.

Configure the request

The request() method, made available through the request module, allows us to pass the HTTP method, URL, request params, headers, and the JSON body as an options object. In this code snippet, we'll configure the request:

Note

For more information about endpoints, routes, and request parameters, see Translator Text API 3.0: Languages.

let options = {
    method: 'GET',
    baseUrl: 'https://api.cognitive.microsofttranslator.com/',
    url: 'languages',
    qs: {
      'api-version': '3.0',
    },
    headers: {
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    json: true,
};

If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. Learn more about authenticating with the multi-service subscription.

Make the request and print the response

Next, we'll create the request using the request() method. It takes the options object that we created in the previous section as the first argument, then prints the prettified JSON response.

request(options, function(err, res, body){
    console.log(JSON.stringify(body, null, 4));
});

Note

In this sample, we're defining the HTTP request in the options object. However, the request module also supports convenience methods, like .post and .get. For more information, see convenience methods.

Put it all together

That's it, you've put together a simple program that will call the Translator Text API and return a JSON response. Now it's time to run your program:

node get-languages.js

If you'd like to compare your code against ours, the complete sample is available on GitHub.

Sample response

Find the country/region abbreviation in this list of languages.

This sample has been truncated to show a snippet of the result:

{
    "translation": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr"
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl"
        },
        ...
    },
    "transliteration": {
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "scripts": [
                {
                    "code": "Arab",
                    "name": "Arabic",
                    "nativeName": "العربية",
                    "dir": "rtl",
                    "toScripts": [
                        {
                            "code": "Latn",
                            "name": "Latin",
                            "nativeName": "اللاتينية",
                            "dir": "ltr"
                        }
                    ]
                },
                {
                    "code": "Latn",
                    "name": "Latin",
                    "nativeName": "اللاتينية",
                    "dir": "ltr",
                    "toScripts": [
                        {
                            "code": "Arab",
                            "name": "Arabic",
                            "nativeName": "العربية",
                            "dir": "rtl"
                        }
                    ]
                }
            ]
        },
      ...
    },
    "dictionary": {
        "af": {
            "name": "Afrikaans",
            "nativeName": "Afrikaans",
            "dir": "ltr",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
        "ar": {
            "name": "Arabic",
            "nativeName": "العربية",
            "dir": "rtl",
            "translations": [
                {
                    "name": "English",
                    "nativeName": "English",
                    "dir": "ltr",
                    "code": "en"
                }
            ]
        },
      ...
    }
}

Clean up resources

If you've hardcoded your subscription key into your program, make sure to remove the subscription key when you're finished with this quickstart.

Next steps

Take a look at the API reference to understand everything you can do with the Translator Text API.

Prerequisites

This quickstart requires:

Create a project and import required modules

Create a new Go project using your favorite IDE or editor or new folder on your desktop. Then copy this code snippet into your project/folder in a file named get-languages.go.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "net/url"
)

Create the main function

Let's create the main function for our application. You'll notice it's a single line of code. That's because we're creating a single function to get and print the list of supported languages for Translator Text.

Copy this code into your project:

func main() {
    /*
     * This calls our getLanguages function, which we'll
     * create in the next section. It takes a single argument,
     * the subscription key.
     */
    getLanguages()
}

Create a function to get a list of supported languages

Let's create a function to get a list of supported languages.

func getLanguages() {
    /*  
     * In the next few sections, we'll add code to this
     * function to make a request and handle the response.
     */
}

Next, let's construct the URL. The URL is built using the Parse() and Query() methods.

Copy this code into the getLanguages function.

// Build the request URL. See: https://golang.org/pkg/net/url/#example_URL_Parse
u, _ := url.Parse("https://api.cognitive.microsofttranslator.com/languages")
q := u.Query()
q.Add("api-version", "3.0")
u.RawQuery = q.Encode()

Note

For more information about endpoints, routes, and request parameters, see Translator Text API 3.0: Languages.

Build the request

Now that you've encoded the request body as JSON, you can build your POST request, and call the Translator Text API.

// Build the HTTP GET request
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
    log.Fatal(err)
}
// Add required headers
req.Header.Add("Content-Type", "application/json")

// Call the Translator Text API
res, err := http.DefaultClient.Do(req)
if err != nil {
    log.Fatal(err)
}

If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request parameters. Learn more about authenticating with the multi-service subscription.

Handle and print the response

Add this code to the getLanguages function to decode the JSON response, and then format and print the result.

// Decode the JSON response
var result interface{}
if err := json.NewDecoder(res.Body).Decode(&result); err != nil {
    log.Fatal(err)
}
// Format and print the response to terminal
prettyJSON, _ := json.MarshalIndent(result, "", "  ")
fmt.Printf("%s\n", prettyJSON)

Put it all together

That's it, you've put together a simple program that will call the Translator Text API and return a JSON response. Now it's time to run your program:

go run get-languages.go

If you'd like to compare your code against ours, the complete sample is available on GitHub.

Sample response

Find the country/region abbreviation in this list of languages.

A successful response is returned in JSON as shown in the following example:

{
  "dictionary": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl",
      "translations": [
        {
          "name": "English",
          "nativeName": "English",
          "dir": "ltr",
          "code": "en"
        }
      ]
    },
...
  },
  "translation": {
    "af": {
      "name": "Afrikaans",
      "nativeName": "Afrikaans",
      "dir": "ltr"
    },
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "dir": "rtl"
    },
...
  },
  "transliteration": {
    "ar": {
      "name": "Arabic",
      "nativeName": "العربية",
      "scripts": [
        {
          "code": "Arab",
          "name": "Arabic",
          "nativeName": "العربية",
          "dir": "rtl",
          "toScripts": [
            {
              "code": "Latn",
              "name": "Latin",
              "nativeName": "اللاتينية",
              "dir": "ltr"
            }
          ]
        },
        {
          "code": "Latn",
          "name": "Latin",
          "nativeName": "اللاتينية",
          "dir": "ltr",
          "toScripts": [
            {
              "code": "Arab",
              "name": "Arabic",
              "nativeName": "العربية",
              "dir": "rtl"
            }
          ]
        }
      ]
    },
...
  }
}

Next steps

Take a look at the API reference to understand everything you can do with the Translator Text API.

See also