Programmatically translate text using the Translator Text API

Page creation date :

What to prepare in advance

Create a Microsoft Azure account beforehand. The creation procedure is described on this page.

Also, this time we will register with the free version, so please change it in a timely manner if you want to use the paid version.

Create API resources

Open the Microsoft Azure portal and click New in the left menu.


Select Intelligence + Analytics from the expanded menu.

「Intelligence + analytics」を選択

From the expanded menu, select Cognitive Services APIs (Preview).

「Cognitive Services APIs (プレビュー)」を選択

When the creation screen appears, enter a name of your choice (it will be the display name on the dashboard) and select "Free Trial" for the subscription. Then click API type.

API type をクリック

Select Translator Text API from the list of APIs.

「Translator Text API」を選択

Then select Pricing tier.

Pricing tier を選択

Since you are using the free version, click "F0 Free" and click the "Select" button. The free version can convert up to 2 million characters per month.

「F0 Free」を選択

If you are registering a service for the first time, create a new Resource group. You can group the resources you create into groups of any name.

A location is a place to put a service. When developing mainly in Japan, it is more likely to improve performance if it is installed in a Japan.

Finally, check "Pin to dashboard" and click the "Create" button.


The dashboard has the resource you created earlier, so click it to open it.


I think the Overview is open, so check the URL for "Endpoint" on the right. This is the URL of the API that should be accessed by authentication first. However, it rarely changes, and it is described in the program that I will introduce later, so it is good to remember that it is here for the time being.


Select Keys from the menu.


Make a note of the KEY 1 that appears and use it to authenticate. I think having two keys is probably a reserve. By the way, if the key leaks to the outside for some reason, you can recreate it with "Regenerate..." above.

「KEY 1」をメモ

This concludes the setup on the Azure side.

Programmatically access the API to translate text

Now it's time to actually create a program so that you can translate the text. Use Visual Studio 2015 to create a WPF application and create a screen that looks like this:

Enter text in From, and in Language, enter which language you want to convert to which language. And if you click on the "Convert Run" button, you will be able to see the translated text in the "Destination" below.

XAML (MainWindow.xaml)

It does not directly affect the translation, so only the code is included.

<Window x:Class="AzureTranslatorTextApi.MainWindow"
    Title="MainWindow" Height="350" Width="525">
      <RowDefinition Height="auto"/>
      <RowDefinition Height="*"/>
      <RowDefinition Height="auto"/>
      <RowDefinition Height="auto"/>
      <RowDefinition Height="auto"/>
      <RowDefinition Height="*"/>
    <Label x:Name="label" Content="変換元" HorizontalAlignment="Left" Grid.Row="0"/>
    <TextBox x:Name="textBoxInput" Margin="4" Text="ここに変換するテキストを入力します。" Grid.Row="1" AcceptsReturn="True" AcceptsTab="True" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"/>
    <Label x:Name="labelLang" Content="言語" HorizontalAlignment="Left" Grid.Row="2"/>
    <Label x:Name="labelLangFrom" Content="from" HorizontalAlignment="Left" Grid.Row="2" Margin="56,0,0,0"/>
    <TextBox x:Name="textBoxLangFrom" Margin="96,4,0,4"  HorizontalAlignment="Left" Text="ja" Grid.Row="2" Width="50"/>
    <Label x:Name="labelLangTo" Content="to" HorizontalAlignment="Left" Grid.Row="2" Margin="164,0,0,0"/>
    <TextBox x:Name="textBoxLangTo" Margin="190,4,0,4"  HorizontalAlignment="Left" Text="en" Grid.Row="2" Width="50" />
    <Button x:Name="button" Content="変換実行"  Margin="24,4" Height="24" Grid.Row="3" Click="button_Click"/>
    <Label x:Name="label_Copy" Content="変換先" HorizontalAlignment="Left" Grid.Row="4"/>
    <TextBox x:Name="textBoxOutput" Margin="4" Grid.Row="5" AcceptsReturn="True" AcceptsTab="True" VerticalScrollBarVisibility="Auto" IsReadOnly="True" Background="#FFE8E8E8" HorizontalScrollBarVisibility="Auto"/>

Get Access Token (MainWindow.xaml.cs)

The basic flow for text translation is as follows:

  1. Throw KEY 1 into the API to get an access token.
  2. Use the access token to throw the text to the translation service to get the translated text.
  3. Get the access token again if needed

It comes to.

First, let's define a method to get an access token and make it easy to use. If you pass the KEY 1 obtained earlier as the argument, you can get the access token. It can also be obtained by synchronous processing, but since C# 5.0 async/await can be used, let's make it an asynchronous process easily.

As a point, set the URL to Endpoint + "/issueToken" as confirmed in Azure, and set KEY 1 obtained with "Ocp-Apim-Subscription-Key" as the key in the header to be sent.

As a response, the string of the access token can be obtained as it is, so it is used as the return value. By the way, this access token is only valid for 10 minutes.

/// <summary>
/// 非同期でアクセストークンを取得します。
/// </summary>
/// <param name="subscriptionKey">認証に必要なキー文字列。</param>
/// <returns>取得したアクセストークン。</returns>
private async Task<string> GetAccessTokenAsync(string subscriptionKey)
  using (var client = new HttpClient())
  using (var request = new HttpRequestMessage())
    request.Method = HttpMethod.Post;
    request.RequestUri = new Uri("");
    request.Content = new StringContent(string.Empty);
    request.Headers.TryAddWithoutValidation("Ocp-Apim-Subscription-Key", subscriptionKey);
    using (var response = await client.SendAsync(request))
      var token = await response.Content.ReadAsStringAsync();


      return token;

Access the API for text translation (MainWindow.xaml.cs)

This is also made into a method to make it easy to use. The arguments allow you to specify the access token you get and the text to translate, and which language to convert to which language.

Note that the URL you access is different from the URL where you obtained the token. The text and language to be translated are sent as a query string in the URL, so escape them using "Uri.EscapeDataString" in advance.

The GET method then sends the Authorization of the Header with the schema "Bearer" and the token in the parameter.

Since the response is taken in XML format, XDocument is used to retrieve the translated text inside. However, if the text contains XML escape characters, perhaps because you are using XML, they may remain escaped. Convert it as needed.

/// <summary>
/// テキストを翻訳します。
/// </summary>
/// <param name="token">API のアクセスに必要なトークン。</param>
/// <param name="text">翻訳するテキスト、</param>
/// <param name="fromLang">翻訳元の言語。</param>
/// <param name="toLang">翻訳先の言語。</param>
/// <returns>翻訳されたテキスト。</returns>
private async Task<string> TranslateText(string token, string text, string fromLang, string toLang)
  using (var client = new HttpClient())
  using (var request = new HttpRequestMessage())
    // URL につけて送信するのでエンコードする
    var escapeText = Uri.EscapeDataString(text);

    var uriStr = ""
      + $"text={escapeText}&from={fromLang}&to={toLang}";

    request.Method = HttpMethod.Get;
    request.RequestUri = new Uri(uriStr);
    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
    using (var response = await client.SendAsync(request))
      var resultText = await response.Content.ReadAsStringAsync();

      // <string>XXXXXX</string> 形式で取得されるので XDocument で操作する
      XDocument xdoc = XDocument.Parse(resultText);


      // XML エスケープ対象文字が正しく変換されない場合があるので
      // 必要があれば対処すること
      return xdoc.Descendants().First().Value;

Button execution process (MainWindow.xaml.cs)

Once you've implemented two methods, all you have to do is call each one. You can translate text by setting KEY1 and specifying the entered value for each method. Since it is an asynchronous process, please add async to the button handling method.

private async void button_Click(object sender, RoutedEventArgs e)
  // ここに認証キー(KEY1)を入力してください
  string subscriptionKey = "XXXXXXXXX";

  // アクセストークンを取得します。有効時間は10分程度です。(おそらく)
  var token = await GetAccessTokenAsync(subscriptionKey);

  // テキストを翻訳し表示します
  textBoxOutput.Text = await TranslateText(token, textBoxInput.Text, textBoxLangFrom.Text, textBoxLangTo.Text);

List of translatable languages

You may want to refer to the following Micorsoft pages: Since it is one of the cloud services, it may be changed at any time.