Quickstart: Use the Translator Text API to transliterate text

In this quickstart, you'll learn how to transliterate (convert) text from one script to another using the Translator Text REST API. In the sample provided, Japanese is transliterated to use the Latin alphabet.

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 transliterate-sample
cd transliterate-sample

The first command does two things. It creates a new .NET console application, and creates a directory named transliterate-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 transliterate-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 transliterate-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 class that's 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 TransliterationResult
{
    public string Text { get; set; }
    public string Script { get; set; }
}

Create a function to transliterate text

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

static public async Task TransliterateTextRequest(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

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.
TransliterationResult[] deserializedOutput = JsonConvert.DeserializeObject<TransliterationResult[]>(result);
// Iterate over the deserialized results.
foreach (TransliterationResult o in deserializedOutput)
{
    Console.WriteLine("Transliterated to {0} script: {1}", o.Script, o.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 TransliterateTextRequest() in the Main function. In this sample, we're transliterating from Japanese to latin script. 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-transliterate
    string subscriptionKey = "YOUR_TRANSLATOR_TEXT_KEY_GOES_HERE";
    string host = "https://api.cognitive.microsofttranslator.com";
    string route = "/transliterate?api-version=3.0&language=ja&fromScript=jpan&toScript=latn";
    string textToTransliterate = @"こんにちは";
    await TransliterateTextRequest(subscriptionKey, host, route, textToTransliterate);
}

You'll notice that in Main, you're declaring subscriptionKey, host, route, and the script to transliterate textToTransliterate.

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:

Transliterated to latn script: Kon\'nichiwa

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

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

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 transliterate-sample
cd transliterate-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 = "Transliterate"
}
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 Transliterate.java.

Import required libraries

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

Add these lines to the Transliterate 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 input language, and the scripts for transliteration. In this sample, it's set to Japanese (jpan) and Latin (latn). Make sure you update the subscription key value.

String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
String url = "https://api.cognitive.microsofttranslator.com/transliterate?api-version=3.0&language=ja&fromScript=jpan&toScript=latn";

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 Transliterate 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 transliteration.

// 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\": \"こんにちは\"\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 {
        Transliterate transliterateRequest = new Transliterate();
        String response = transliterateRequest.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

[
  {
    "text": "konnichiwa",
    "script": "latn"
  }
]

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 project using your favorite IDE or editor, or a new folder with a file named transliterate-text.py on your desktop. Then copy this code snippet into your project/file:

# -*- 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 transliterate route and identifies that we want to hit version 3 of the API.

The params are used to set the input language, and the input and output scripts. In this sample, we're transliterating from Japanese to the Latin alphabet.

Note

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

base_url = 'https://api.cognitive.microsofttranslator.com'
path = '/transliterate?api-version=3.0'
params = '&language=ja&fromScript=jpan&toScript=latn'
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 transliterate text

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

# Transliterate "good afternoon" from source Japanese.
# Note: You can pass more than one object in body.
body = [{
    'text': 'こんにちは'
}]

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 transliterate-text.py

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

Sample response

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

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

let options = {
    method: 'POST',
    baseUrl: 'https://api.cognitive.microsofttranslator.com/',
    url: 'transliterate',
    qs: {
      'api-version': '3.0',
      'language': 'ja',
      'fromScript': 'jpan',
      'toScript': 'latn'
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'こんにちは'
    }],
    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 transliterate-text.js

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

Sample response

[
    {
        "script": "latn",
        "text": "konnichiwa"
    }
]

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 transliterate-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 transliterate function, which we'll
     * create in the next section. It takes a single argument,
     * the subscription key.
     */
    transliterate(subscriptionKey)
}

Create a function to transliterate text

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

func transliterate(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, we're transliterating from Japanese to the Latin alphabet.

Copy this code into the transliterate function.

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

Note

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

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 transliterate function.

// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
	Text string
}{
	{Text: "こんにちは"},
}
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 transliterate 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 transliterate-text.go

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

Sample response

[
  {
    "script": "latn",
    "text": "konnichiwa"
  }
]

Next steps

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

See also