Quickstart: Use the Translator Text API to detect text language

In this quickstart, you'll learn how to detect the language of provided text with 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 detect-sample
cd detect-sample

The first command does two things. It creates a new .NET console application, and creates a directory named detect-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 detect-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 detect-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 DetectResult
{
    public string Language { get; set; }
    public float Score { get; set; }
    public bool IsTranslationSupported { get; set; }
    public bool IsTransliterationSupported { get; set; }
    public AltTranslations[] Alternatives { get; set; }
}
public class AltTranslations
{
    public string Language { get; set; }
    public float Score { get; set; }
    public bool IsTranslationSupported { get; set; }
    public bool IsTransliterationSupported { get; set; }
}

Create a function to detect the source text's language

Within the Program class, create a function called DetectTextRequest(). This class encapsulates the code used to call the Detect resource and prints the result to console.

static public async Task DetectTextRequest(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 detect request

Next, we need to create and serialize the JSON object that includes the text that will undergo language detection.

System.Object[] body = new System.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.
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.
DetectResult[] deserializedOutput = JsonConvert.DeserializeObject<DetectResult[]>(result);
// Iterate over the deserialized response.
foreach (DetectResult o in deserializedOutput)
{
    Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.\nTranslation supported: {2}.\nTransliteration supported: {3}.\n",
        o.Language, o.Score, o.IsTranslationSupported, o.IsTransliterationSupported);
    // Create a counter
    int counter = 0;
    // Iterate over alternate translations.
    foreach (AltTranslations a in o.Alternatives)
    {
        counter++;
        Console.WriteLine("Alternative {0}", counter);
        Console.WriteLine("The detected language is '{0}'. Confidence is: {1}.\nTranslation supported: {2}.\nTransliteration supported: {3}.\n",
            a.Language, a.Score, a.IsTranslationSupported, a.IsTransliterationSupported);
    }
}

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 DetectTextRequest() in the Main function. 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.
    string subscriptionKey = "YOUR_TRANSLATOR_TEXT_KEY_GOES_HERE";
    string host = "https://api.cognitive.microsofttranslator.com";
    string route = "/detect?api-version=3.0";
    string breakSentenceText = @"How are you doing today? The weather is pretty pleasant. Have you been to the movies lately?";
    await DetectTextRequest(subscriptionKey, host, route, breakSentenceText);
}

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:

Note

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

The detected language is 'en'. Confidence is: 1.
Translation supported: True.
Transliteration supported: False.

Alternative 1
The detected language is 'fil'. Confidence is: 0.82.
Translation supported: True.
Transliteration supported: False.

Alternative 2
The detected language is 'ro'. Confidence is: 1.
Translation supported: True.
Transliteration supported: False.

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

[  
    {  
        "language":"en",
        "score":1.0,
        "isTranslationSupported":true,
        "isTransliterationSupported":false,
        "alternatives":[  
            {  
                "language":"fil",
                "score":0.82,
                "isTranslationSupported":true,
                "isTransliterationSupported":false
            },
            {  
                "language":"ro",
                "score":1.0,
                "isTranslationSupported":true,
                "isTransliterationSupported":false
            }
        ]
    }
]

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 detect-sample
cd detect-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 = "Detect"
}
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 Detect.java.

Import required libraries

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

Add these lines to the Detect class:

String subscriptionKey = "YOUR_SUBSCRIPTION_KEY";
String url = "https://api.cognitive.microsofttranslator.com/detect?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 Detect 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 language detection.

// 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\": \"Salve mondo!\"\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 {
        Detect detectRequest = new Detect();
        String response = detectRequest.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

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

[
  {
    "language": "it",
    "score": 1.0,
    "isTranslationSupported": true,
    "isTransliterationSupported": false,
    "alternatives": [
      {
        "language": "pt",
        "score": 1.0,
        "isTranslationSupported": true,
        "isTransliterationSupported": false
      },
      {
        "language": "en",
        "score": 1.0,
        "isTranslationSupported": true,
        "isTransliterationSupported": false
      }
    ]
  }
]

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 detect.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 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 detect 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: Detect.

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

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 detect text language

Define the string (or strings) that you want to detect the language for:

# You can pass more than one object in body.
body = [{
    'text': 'Salve, mondo!'
}]

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 detect.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.

[
    {
        "alternatives": [
            {
                "isTranslationSupported": true,
                "isTransliterationSupported": false,
                "language": "pt",
                "score": 1.0
            },
            {
                "isTranslationSupported": true,
                "isTransliterationSupported": false,
                "language": "en",
                "score": 1.0
            }
        ],
        "isTranslationSupported": true,
        "isTransliterationSupported": false,
        "language": "it",
        "score": 1.0
    }
]

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 detect.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.

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

let options = {
    method: 'POST',
    baseUrl: 'https://api.cognitive.microsofttranslator.com/',
    url: 'detect',
    qs: {
      'api-version': '3.0',
    },
    headers: {
      'Ocp-Apim-Subscription-Key': subscriptionKey,
      'Content-type': 'application/json',
      'X-ClientTraceId': uuidv4().toString()
    },
    body: [{
          'text': 'Salve, mondo!'
    }],
    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 detect.js

Sample response

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

[
    {
        "alternatives": [
            {
                "isTranslationSupported": true,
                "isTransliterationSupported": false,
                "language": "pt",
                "score": 1.0
            },
            {
                "isTranslationSupported": true,
                "isTransliterationSupported": false,
                "language": "en",
                "score": 1.0
            }
        ],
        "isTranslationSupported": true,
        "isTransliterationSupported": false,
        "language": "it",
        "score": 1.0
    }
]

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

Create a function to detect the text language

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

func detect(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.

Copy this code into the detect function.

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

Note

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

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

// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
    Text string
}{
    {Text: "Salve, Mondo!"},
}
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
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 detect 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 detect-language.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.

[
  {
    "alternatives": [
      {
        "isTranslationSupported": true,
        "isTransliterationSupported": false,
        "language": "pt",
        "score": 1
      },
      {
        "isTranslationSupported": true,
        "isTransliterationSupported": false,
        "language": "en",
        "score": 1
      }
    ],
    "isTranslationSupported": true,
    "isTransliterationSupported": false,
    "language": "it",
    "score": 1
  }
]

Next steps

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

See also