Translating text from a program using the Translator Text API

Page creation date :

What to prepare in advance

Create a Microsoft Azure account beforehand. Instructions こちらのページ are described here on how to create.

In addition, because i register in the free version this time, please change it in a timely time if you want to use the paid version.

Create API resources

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


Select Intelligence + analytics from the expanded menu.

「Intelligence + analytics」を選択

Select Cognitive Services APIs (Preview) from the expanded menu.

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

The create screen appears, enter any account name (which will be the display name in the dashboard) and select "Free Trial" for your 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 を選択

Because I use the free version, I click "F0 Free" and click "Select" button. The free version can be converted to 2 million characters per month.

「F0 Free」を選択

If this is your first time registering the service, create a new Resource group. You can group resources by any name.

The location is where the service is located. If you are expanding mainly in Japan, it is more likely that you will improve your performance if you set it up in Japan.

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


You've just created a resource in the dashboard, so click to open it.


I think the Overview is open, so check the Endpoint URL to 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 introduced later, so it is good to remember that it is here once.


Select Keys from the menu.


Make a note of the "KEY 1" displayed. Use this key to authenticate. I think it's probably a reserve that has two keys. By the way, if the key leaks outside for some reason, you can recreate it with "Regenerate..." above.

「KEY 1」をメモ

This is the end of the Azure configuration.

Access the API programmatically to translate text

Now you can actually write a program so that you can translate the text. Use Visual Studio 2015 to create a WPF application and create a screen similar to the following:

Enter text in Source, and then type which language to convert to in the Language. Then, when you click the "Run Convert" button, the translated text will be displayed in the "Destination" below.

XAML (MainWindow.xaml)

It does not directly affect the translation, so only the code will be 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"/>

Access Token Acquisition (MainWindow.xaml.cs)

As a basic flow for text translation

  1. Toget the access token by throwing KEY 1 into the API.
  2. Use an access token to throw text into the translation service to get the translated text.
  3. Get the access token again if necessary

It comes to.

First, let's define a method to get the access token to make it easier to use. Passing key 1, which you just got, allows you to obtain an access token. You can also get it synchronously, but from C# 5.0 you can use async/await, so let's make it asynchronous.

The point is to set endpoint +"/issueToken" as confirmed in Azure for the URL, and set key 1 with "Ocp-Apim-Subscription-Key" as the key for the header you want to send.

As a response, the string of the access token can be retrieved as it is, so it is the return value. By the way, this access token is valid only 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 to translate text (MainWindow.xaml.cs)

This is also a method to make it easier to use. Allows you to specify the access token obtained for the argument, the text to translate, and which language to convert to.

Note that the URL you access is different from the URL where you got the token. The text and language you want to translate will be sent as a query string in the URL, so escape using Uri.EscapeDataString in advance.

The rest is the GET method that sends the Schema "Bearer" and the parameter to the Authorization of header with a token.

Because the response is retrieved in XML format, xdocument is used to retrieve the translated text in. However, if the text contains xml escape characters probably because you are using XML, it may remain escaped. Convert 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 have implemented two methods, all you have to do is call each one. You can translate the text by setting KEY1 and specifying the values entered in each method. Once it's asynchronous, put async on the button processing 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 languages that can be translated

Refer to the following micorsoft pages: Because it is one of the cloud services, it is subject to change from time to time.