Quickstart: Use the Translator Text API to translate text

In this quickstart, you'll learn how to translate a text string from English to German, Italian, Japanese and Thai using the Translator Text REST API.

This quickstart requires an Azure Cognitive Services account with a Translator Text resource. If you don't have an account, you can use the free trial to get a subscription key.

Prerequisites

Create a .NET Core project

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

dotnet new console -o translate-sample
cd translate-sample

The first command does two things. It creates a new .NET console application, and creates a directory named translate-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

Select the C# language version

This quickstart requires C# 7.1 or later. There are a few ways to change the C# version for your project. In this guide, we'll show you how to adjust the translate-sample.csproj file. For all available options, such as changing the language in Visual Studio, see Select the C# language version.

Open your project, then open translate-sample.csproj. Make sure that LangVersion is set to 7.1 or later. If there isn't a property group for the language version, add these lines:

<PropertyGroup>
   <LangVersion>7.1</LangVersion>
</PropertyGroup>

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 System.Threading.Tasks;
// Install Newtonsoft.Json with NuGet
using Newtonsoft.Json;

Create classes for the JSON response

Next, we're going to create a set of classes that are used when deserializing the JSON response returned by the Translator Text API.

/// <summary>
/// The C# classes that represents the JSON returned by the Translator Text API.
/// </summary>
public class TranslationResult
{
    public DetectedLanguage DetectedLanguage { get; set; }
    public TextResult SourceText { get; set; }
    public Translation[] Translations { get; set; }
}

public class DetectedLanguage
{
    public string Language { get; set; }
    public float Score { get; set; }
}

public class TextResult
{
    public string Text { get; set; }
    public string Script { get; set; }
}

public class Translation
{
    public string Text { get; set; }
    public TextResult Transliteration { get; set; }
    public string To { get; set; }
    public Alignment Alignment { get; set; }
    public SentenceLength SentLen { get; set; }
}

public class Alignment
{
    public string Proj { get; set; }
}

public class SentenceLength
{
    public int[] SrcSentLen { get; set; }
    public int[] TransSentLen { get; set; }
}

Create a function to translate text

Within the Program class, create an asynchronous function called TranslateTextRequest(). This function takes four arguments: subscriptionKey, host, route, and inputText.

// This sample requires C# 7.1 or later for async/await.
// Async call to the Translator Text API
static public async Task TranslateTextRequest(string subscriptionKey, string host, string route, string inputText)
{
  /*
   * The code for your call to the translation service will be added to this
   * function in the next few sections.
   */
}

Serialize the translation request

Next, we need to create and serialize the JSON object that includes the text you want to translate. Keep in mind, you can pass more than one object in the body.

object[] body = new object[] { new { Text = inputText } };
var requestBody = JsonConvert.SerializeObject(body);

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
  • Insert the request body (serialized JSON object)
  • Add required headers
  • Make an asynchronous request
  • Print the response using the classes you created earlier

Add this code to the HttpRequestMessage:

// Build the request.
// Set the method to Post.
request.Method = HttpMethod.Post;
// Construct the URI and add headers.
request.RequestUri = new Uri(host + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);

// Send the request and get response.
HttpResponseMessage response = await client.SendAsync(request).ConfigureAwait(false);
// Read response as a string.
string result = await response.Content.ReadAsStringAsync();
// Deserialize the response using the classes created earlier.
TranslationResult[] deserializedOutput = JsonConvert.DeserializeObject<TranslationResult[]>(result);
// Iterate over the deserialized results.
foreach (TranslationResult o in deserializedOutput)
{
    // Print the detected input language and confidence score.
    Console.WriteLine("Detected input language: {0}\nConfidence score: {1}\n", o.DetectedLanguage.Language, o.DetectedLanguage.Score);
    // Iterate over the results and print each translation.
    foreach (Translation t in o.Translations)
    {
        Console.WriteLine("Translated to {0}: {1}", t.To, t.Text);
    }
}

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.

Put it all together

The last step is to call TranslateTextRequest() in the Main function. In this sample, we're translating to German (de), Italian (it), Japanese (ja), and Thai (th). Locate static void Main(string[] args) and replace it with this code:

static async Task Main(string[] args)
{
    // This is our main function.
    // Output languages are defined in the route.
    // For a complete list of options, see API reference.
    // https://docs.microsoft.com/azure/cognitive-services/translator/reference/v3-0-translate
    string host = "https://api.cognitive.microsofttranslator.com";
    string route = "/translate?api-version=3.0&to=de&to=it&to=ja&to=th";
    string subscriptionKey = "YOUR_TRANSLATOR_TEXT_KEY_GOES_HERE";
    // Prompts you for text to translate. If you'd prefer, you can
    // provide a string as textToTranslate.
    Console.Write("Type the phrase you'd like to translate? ");
    string textToTranslate = Console.ReadLine();
    await TranslateTextRequest(subscriptionKey, host, route, textToTranslate);
}

You'll notice that in Main, you're declaring subscriptionKey, host, and route. Additionally, you're prompting the user for input with Console.Readline() and assigning the value to textToTranslate.

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

After you run the sample, you should see the following printed to terminal:

Detected input language: en
Confidence score: 1

Translated to de: Hallo Welt!
Translated to it: Salve, mondo!
Translated to ja: ハローワールド!
Translated to th: หวัดดีชาวโลก!

This message is built from the raw JSON, which will look like this:

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Hallo Welt!",
        "to": "de"
      },
      {
        "text": "Salve, mondo!",
        "to": "it"
      },
      {
        "text": "ハローワールド!",
        "to": "ja"
      },
      {
        "text": "หวัดดีชาวโลก!",
        "to": "th"
      }
    ]
  }
]

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 translator-sample
cd translator-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 = "Translate"
}
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 Translate.java.

Import required libraries

Open Translate.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 Translate {
  // All project code goes here...
}

Add these lines to the Translate class. You'll notice that along with the api-version, two additional parameters have been appended to the url. These parameters are used to set the translation outputs. In this sample, it's set to German (de) and Italian (it). Make sure you update the subscription key value.

String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
String url = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=de,it";

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 Translate class to instantiate the OkHttpClient:

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

Next, let's build the POST request. Feel free to change the text for translation. The text must be escaped.

// This function performs a POST request.
public String Post() throws IOException {
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody body = RequestBody.create(mediaType,
            "[{\n\t\"Text\": \"Welcome to Microsoft Translator. Guess how many languages I speak!\"\n}]");
    Request request = new Request.Builder()
            .url(url).post(body)
            .addHeader("Ocp-Apim-Subscription-Key", subscriptionKey)
            .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 {
        Translate translateRequest = new Translate();
        String response = translateRequest.Post();
        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

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Willkommen bei Microsoft Translator. Erraten Sie, wie viele Sprachen ich spreche!",
        "to": "de"
      },
      {
        "text": "Benvenuti a Microsoft Translator. Indovinate quante lingue parlo!",
        "to": "it"
      }
    ]
  }
]

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
  • An Azure subscription key for Translator Text

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 translate-text.py. Be sure your IDE's interpreter references the correct version of Python to avoid libraries not being recognized.

# -*- 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 subscription key, base url, and path

This sample will try to read your Translator Text subscription key from the environment variable TRANSLATOR_TEXT_KEY. If you're not familiar with environment variables, you can set subscriptionKey as a string and comment out the conditional statement.

Copy this code into your project:

# Checks to see if the Translator Text subscription key is available
# as an environment variable. If you are setting your subscription key as a
# string, then comment these lines out.
if 'TRANSLATOR_TEXT_KEY' in os.environ:
    subscriptionKey = os.environ['TRANSLATOR_TEXT_KEY']
else:
    print('Environment variable for TRANSLATOR_TEXT_KEY is not set.')
    exit()
# If you want to set your subscription key as a string, uncomment the line
# below and add your subscription key.
#subscriptionKey = 'put_your_key_here'

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

The params are used to set the output languages. In this sample we're translating from English to Italian and German: it and de.

Note

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

base_url = 'https://api.cognitive.microsofttranslator.com'
path = '/translate?api-version=3.0'
params = '&to=de&to=it'
constructed_url = base_url + path + params

Add headers

The easiest way to authenticate a request is to pass in your subscription key as an Ocp-Apim-Subscription-Key header, which is what we use in this sample. As an alternative, you can exchange your subscription key for an access token, and pass the access token along as an Authorization header to validate your request. For more information, see Authentication.

Copy this code snippet into your project:

headers = {
    'Ocp-Apim-Subscription-Key': subscriptionKey,
    '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 translate text

Define the string (or strings) that you want to translate:

body = [{
    'text': 'Hello World!'
}]

Next, we'll create a POST request using the requests module. It takes three arguments: the concatenated URL, the request headers, and the request body:

request = requests.post(constructed_url, headers=headers, json=body)
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 translate-text.py

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

Sample response

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "text": "Hallo Welt!",
                "to": "de"
            },
            {
                "text": "Salve, mondo!",
                "to": "it"
            }
        ]
    }
]

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, or a new folder with a file named translate-text.js on your desktop. Then copy this code snippet into your project/file:

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.

Set the subscription key

This code will try to read your Translator Text subscription key from the environment variable TRANSLATOR_TEXT_KEY. If you're not familiar with environment variables, you can set subscriptionKey as a string and comment out the conditional statement.

Copy this code into your project:

/* Checks to see if the subscription key is available
as an environment variable. If you are setting your subscription key as a
string, then comment these lines out.

If you want to set your subscription key as a string, replace the value for
the Ocp-Apim-Subscription-Key header as a string. */
const subscriptionKey = process.env.TRANSLATOR_TEXT_KEY;
if (!subscriptionKey) {
  throw new Error('Environment variable for your subscription key is not set.')
};

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: Translate.

let options = {
    method: 'POST',
    baseUrl: 'https://api.cognitive.microsofttranslator.com/',
    url: 'translate',
    qs: {
      'api-version': '3.0',
      'to': ['de', 'it']
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'Hello World!'
    }],
    json: true,
};

The easiest way to authenticate a request is to pass in your subscription key as an Ocp-Apim-Subscription-Key header, which is what we use in this sample. As an alternative, you can exchange your subscription key for an access token, and pass the access token along as an Authorization header to validate your request.

If you are using a Cognitive Services multi-service subscription, you must also include the Ocp-Apim-Subscription-Region in your request headers.

For more information, see Authentication.

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 translate-text.js

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

Sample response

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "text": "Hallo Welt!",
                "to": "de"
            },
            {
                "text": "Salve, mondo!",
                "to": "it"
            }
        ]
    }
]

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:

  • Go
  • An Azure subscription key for Translator Text

Create a project and import required modules

Create a new Go project using your favorite IDE or editor. Then copy this code snippet into your project in a file named translate-text.go.

package main

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

Create the main function

This sample will try to read your Translator Text subscription key from the environment variable TRANSLATOR_TEXT_KEY. If you're not familiar with environment variables, you can set subscriptionKey as a string and comment out the conditional statement.

Copy this code into your project:

func main() {
    /*
     * Read your subscription key from an env variable.
     * Please note: You can replace this code block with
     * var subscriptionKey = "YOUR_SUBSCRIPTION_KEY" if you don't
     * want to use env variables. If so, be sure to delete the "os" import.
     */
    subscriptionKey := os.Getenv("TRANSLATOR_TEXT_KEY")
    if subscriptionKey == "" {
       log.Fatal("Environment variable TRANSLATOR_TEXT_KEY is not set.")
    }
    /*
     * This calls our translate function, which we'll
     * create in the next section. It takes a single argument,
     * the subscription key.
     */
    translate(subscriptionKey)
}

Create a function to translate text

Let's create a function to translate text. This function will take a single argument, your Translator Text subscription key.

func translate(subscriptionKey string) {
    /*  
     * 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. You'll notice that parameters are added with the Add() method. In this sample, you're translating from English to German and Italian: de and it.

Copy this code into the translate function.

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

Note

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

Create a struct for your request body

Next, create an anonymous structure for the request body and encode it as JSON with json.Marshal(). Add this code to the translate function.

// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
	Text string
}{
	{Text: "Hello, world!"},
}
b, _ := json.Marshal(body)

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 POST request
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(b))
if err != nil {
    log.Fatal(err)
}
// Add required headers to the request
req.Header.Add("Ocp-Apim-Subscription-Key", subscriptionKey)
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 translate 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 translate-text.go

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

Sample response

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

[
  {
    "detectedLanguage": {
      "language": "en",
      "score": 1.0
    },
    "translations": [
      {
        "text": "Hallo Welt!",
        "to": "de"
      },
      {
        "text": "Salve, mondo!",
        "to": "it"
      }
    ]
  }
]

Next steps

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

See also