In this quickstart, you learn to use the Translator service via REST. You start with basic examples and move onto some core configuration options that are commonly used during development, including:
Once you have an Azure subscription, create a Translator resource in the Azure portal to get your key and endpoint. After it deploys, select Go to resource.
You'll need the key and endpoint from the resource to connect your application to the Translator service. You'll paste your key and endpoint into the code below later in the quickstart. You can find these values on the Azure portal Keys and Endpoint page:
You can use the free pricing tier (F0) to try the service, and upgrade later to a paid tier for production.
Create a Java file and copy in the code from the provided sample. Don't forget to add your key.
Run the sample: gradle run.
Create a new project in your favorite IDE or editor.
Copy the code from one of the samples into your project.
Set your key.
Run the program. For example: node Translate.js.
Create a new project in your favorite IDE or editor.
Copy the code from one of the samples into your project.
Set your key.
Run the program. For example: python translate.py.
Headers
When calling the Translator service via REST, you'll need to make sure the following headers are included with each request. Don't worry, we'll include the headers in the sample code in the following sections.
Required request header. Specifies the content type of the payload. Accepted value is application/json; charset=UTF-8.
Content-Length
Required request header. The length of the request body.
X-ClientTraceId
Optional. A client-generated GUID to uniquely identify the request. You can omit this header if you include the trace ID in the query string using a query parameter named ClientTraceId.
Keys and endpoints
The samples on this page use hard-coded keys and endpoints for simplicity. Remember to remove the key from your code when you're done, and never post it publicly. For production, consider using a secure way of storing and accessing your credentials. See the Cognitive Services security article for more information.
Translate text
The core operation of the Translator service is to translate text. In this section, you'll build a request that takes a single source (from) and provides two outputs (to). Then we'll review some parameters that can be used to adjust both the request and the response.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// Input and output languages are defined as parameters.
string route = "/translate?api-version=3.0&from=en&to=de&to=it";
string textToTranslate = "Hello, world!";
object[] body = new object[] { new { Text = textToTranslate } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "de")
q.Add("to", "it")
u.RawQuery = q.Encode()
// 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 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Translate {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/translate")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("from", "en")
.addQueryParameter("to", "de")
.addQueryParameter("to", "it")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Hello World!\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'from': 'en',
'to': ['de', 'it']
},
data: [{
'text': 'Hello World!'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'from': 'en',
'to': ['de', 'it']
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Hello World!'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response:
If you know that you'll need translation, but don't know the language of the text that will be sent to the Translator service, you can use the language detection operation. There's more than one way to identify the source text language. In this section, you'll learn how to use language detection using the translate endpoint, and the detect endpoint.
Detect source language during translation
If you don't include the from parameter in your translation request, the Translator service will attempt to detect the source text's language. In the response, you'll get the detected language (language) and a confidence score (score). The closer the score is to 1.0, means that there is increased confidence that the detection is correct.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// Output languages are defined as parameters, input language detected.
string route = "/translate?api-version=3.0&to=de&to=it";
string textToTranslate = "Hello, world!";
object[] body = new object[] { new { Text = textToTranslate } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "de")
q.Add("to", "it")
u.RawQuery = q.Encode()
// 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 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Translate {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/translate")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("to", "de")
.addQueryParameter("to", "it")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Hello World!\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'to': ['de', 'it']
},
data: [{
'text': 'Hello World!'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': ['de', 'it']
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Hello World!'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response:
It's possible to use the Translator service to detect the language of source text without performing a translation. To do this, you'll use the /detect endpoint.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// Just detect language
string route = "/detect?api-version=3.0";
string textToLangDetect = "Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.";
object[] body = new object[] { new { Text = textToLangDetect } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/detect?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal."},
}
b, _ := json.Marshal(body)
// 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Detect {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/detect")
.addQueryParameter("api-version", "3.0")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/detect',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0'
},
data: [{
'text': 'Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/detect'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Ich würde wirklich gern Ihr Auto um den Block fahren ein paar Mal.'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
When using the /detect endpoint, the response will include alternate detections, and will let you know if translation and transliteration are supported for all of the detected languages. After a successful call, you should see the following response:
Transliteration is the process of converting a word or phrase from the script (alphabet) of one language to another based on phonetic similarity. For example, you could use transliteration to convert "สวัสดี" (thai) to "sawatdi" (latn). There's more than one way to perform transliteration. In this section, you'll learn how to use language detection using the translate endpoint, and the transliterate endpoint.
Transliterate during translation
If you're translating into a language that uses a different alphabet (or phonemes) than your source, you might need a transliteration. In this example, we translate "Hello" from English to Thai. In addition to getting the translation in Thai, you'll get a transliteration of the translated phrase using the Latin alphabet.
To get a transliteration from the translate endpoint, use the toScript parameter.
Note
For a complete list of available languages and transliteration options, see language support.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// Output language defined as parameter, with toScript set to latn
string route = "/translate?api-version=3.0&to=th&toScript=latn";
string textToTransliterate = "Hello";
object[] body = new object[] { new { Text = textToTransliterate } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "th")
q.Add("toScript", "latn")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Hello"},
}
b, _ := json.Marshal(body)
// 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Translate {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/translate")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("to", "th")
.addQueryParameter("toScript", "latn")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Hello\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'to': 'th',
'toScript': 'latn'
},
data: [{
'text': 'Hello'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': 'th',
'toScript': 'latn'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Hello'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response. Keep in mind that the response from translate endpoint includes the detected source language with a confidence score, a translation using the alphabet of the output language, and a transliteration using the Latin alphabet.
You can also use the transliterate endpoint to get a transliteration. When using the transliteration endpoint, you must provide the source language (language), the source script/alphabet (fromScript), and the output script/alphabet (toScript) as parameters. In this example, we're going to get the transliteration for สวัสดี.
Note
For a complete list of available languages and transliteration options, see language support.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// For a complete list of options, see API reference.
// Input and output languages are defined as parameters.
string route = "/translate?api-version=3.0&to=th&toScript=latn";
string textToTransliterate = "Hello";
object[] body = new object[] { new { Text = textToTransliterate } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/transliterate?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("language", "th")
q.Add("fromScript", "thai")
q.Add("toScript", "latn")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "สวัสดี"},
}
b, _ := json.Marshal(body)
// 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Transliterate {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/transliterate")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("language", "th")
.addQueryParameter("fromScript", "thai")
.addQueryParameter("toScript", "latn")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"สวัสดี\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/transliterate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'language': 'th',
'fromScript': 'thai',
'toScript': 'latn'
},
data: [{
'text': 'สวัสดี'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/transliterate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'language': 'th',
'fromScript': 'thai',
'toScript': 'latn'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'สวัสดี'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response. Unlike the call to the translate endpoint, transliterate only returns the script and the output text.
[
{
"script": "latn",
"text": "sawatdi"
}
]
Get sentence length
With the Translator service, you can get the character count for a sentence or series of sentences. The response is returned as an array, with character counts for each sentence detected. You can get sentence lengths with the translate and breaksentence endpoints.
Get sentence length during translation
You can get character counts for both source text and translation output using the translate endpoint. To return sentence length (srcSenLen and transSenLen) you must set the includeSentenceLength parameter to True.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// Include sentence length details.
string route = "/translate?api-version=3.0&to=es&includeSentenceLength=true";
string sentencesToCount =
"Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine.";
object[] body = new object[] { new { Text = sentencesToCount } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("to", "es")
q.Add("includeSentenceLength", "true")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine."},
}
b, _ := json.Marshal(body)
// 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class Translate {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/translate")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("to", "es")
.addQueryParameter("includeSentenceLength", "true")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
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);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'to': 'es',
'includeSentenceLength': true
},
data: [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': 'es',
'includeSentenceLength': True
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response. In addition to the detected source language and translation, you'll get character counts for each detected sentence for both the source (srcSentLen) and translation (transSentLen).
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// Only include sentence length details.
string route = "/breaksentence?api-version=3.0";
string sentencesToCount =
"Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine.";
object[] body = new object[] { new { Text = sentencesToCount } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/breaksentence?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Can you tell me how to get to Penn Station? Oh, you aren't sure? That's fine."},
}
b, _ := json.Marshal(body)
// 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class BreakSentence {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/breaksentence")
.addQueryParameter("api-version", "3.0")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
public static void main(String[] args) {
try {
BreakSentence breakSentenceRequest = new BreakSentence();
String response = breakSentenceRequest.Post();
System.out.println(prettify(response));
} catch (Exception e) {
System.out.println(e);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/breaksentence',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0'
},
data: [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/breaksentence'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'Can you tell me how to get to Penn Station? Oh, you aren\'t sure? That\'s fine.'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response. Unlike the call to the translate endpoint, breaksentence only returns the character counts for the source text in an array called sentLen.
With the endpoint, you can get alternate translations for a word or phrase. For example, when translating the word "shark" from en to es, this endpoint returns both "tiburón" and "escualo".
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// See many translation options
string route = "/dictionary/lookup?api-version=3.0&from=en&to=es";
string wordToTranslate = "shark";
object[] body = new object[] { new { Text = wordToTranslate } };
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/dictionary/lookup?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "es")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "shark"},
}
b, _ := json.Marshal(body)
// 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class DictionaryLookup {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/dictionary/lookup")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("from", "en")
.addQueryParameter("to", "es")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Shark\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
public static void main(String[] args) {
try {
DictionaryLookup dictionaryLookupRequest = new DictionaryLookup();
String response = dictionaryLookupRequest.Post();
System.out.println(prettify(response));
} catch (Exception e) {
System.out.println(e);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/dictionary/lookup',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'from': 'en',
'to': 'es'
},
data: [{
'text': 'shark'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/dictionary/lookup'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'from': 'en',
'to': 'es'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'shark'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response. Let's break this down since the JSON is more complex than some of the other examples in this article. The translations array includes a list of translations. Each object in this array includes a confidence score (confidence), the text optimized for end-user display (displayTarget), the normalized text (normalizedText), the part of speech (posTag), and information about previous translation (backTranslations). For more information about the response, see Dictionary Lookup
After you've performed a dictionary lookup, you can pass the source text and translation to the dictionary/examples endpoint to get a list of examples that show both terms in the context of a sentence or phrase. Building on the previous example, you'll use the normalizedText and normalizedTarget from the dictionary lookup response as text and translation respectively. The source language (from) and output target (to) parameters are required.
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "YOUR-KEY";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com/";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static readonly string location = "YOUR_RESOURCE_LOCATION";
static async Task Main(string[] args)
{
// See examples of terms in context
string route = "/dictionary/examples?api-version=3.0&from=en&to=es";
object[] body = new object[] { new { Text = "Shark", Translation = "tiburón" } } ;
var requestBody = JsonConvert.SerializeObject(body);
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
// Build the request.
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
request.Headers.Add("Ocp-Apim-Subscription-Key", key);
request.Headers.Add("Ocp-Apim-Subscription-Region", location);
// 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();
Console.WriteLine(result);
}
}
}
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
)
func main() {
key := "YOUR-KEY"
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
location := "YOUR_RESOURCE_LOCATION";
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/dictionary/examples?api-version=3.0"
// Build the request URL. See: https://go.dev/pkg/net/url/#example_URL_Parse
u, _ := url.Parse(uri)
q := u.Query()
q.Add("from", "en")
q.Add("to", "es")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
Translation string
}{
{
Text: "Shark",
Translation: "tiburón",
},
}
b, _ := json.Marshal(body)
// 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", key)
req.Header.Add("Ocp-Apim-Subscription-Region", location)
req.Header.Add("Content-Type", "application/json")
// Call the Translator Text API
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
// 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)
}
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.gson.*;
import com.squareup.okhttp.*;
public class DictionaryExamples {
private static String key = "YOUR_KEY";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
private static String location = "YOUR_RESOURCE_LOCATION";
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("api.cognitive.microsofttranslator.com")
.addPathSegment("/dictionary/examples")
.addQueryParameter("api-version", "3.0")
.addQueryParameter("from", "en")
.addQueryParameter("to", "es")
.build();
// Instantiates the OkHttpClient.
OkHttpClient client = new OkHttpClient();
// This function performs a POST request.
public String Post() throws IOException {
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"[{\"Text\": \"Shark\", \"Translation\": \"tiburón\"}]");
Request request = new Request.Builder().url(url).post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
.addHeader("Ocp-Apim-Subscription-Region", location)
.addHeader("Content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
// 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);
}
public static void main(String[] args) {
try {
DictionaryExamples dictionaryExamplesRequest = new DictionaryExamples();
String response = dictionaryExamplesRequest.Post();
System.out.println(prettify(response));
} catch (Exception e) {
System.out.println(e);
}
}
}
const axios = require('axios').default;
const { v4: uuidv4 } = require('uuid');
var key = "YOUR_KEY";
var endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using a Cognitive Services resource.
var location = "YOUR_RESOURCE_LOCATION";
axios({
baseURL: endpoint,
url: '/dictionary/examples',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: {
'api-version': '3.0',
'from': 'en',
'to': 'es'
},
data: [{
'text': 'shark',
'translation': 'tiburón'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "YOUR_KEY"
endpoint = "https://api.cognitive.microsofttranslator.com"
# Add your location, also known as region. The default is global.
# This is required if using a Cognitive Services resource.
location = "YOUR_RESOURCE_LOCATION"
path = '/dictionary/examples'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'from': 'en',
'to': 'es'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': str(uuid.uuid4())
}
# You can pass more than one object in body.
body = [{
'text': 'shark',
'translation': 'tiburón'
}]
request = requests.post(constructed_url, params=params, headers=headers, json=body)
response = request.json()
print(json.dumps(response, sort_keys=True, ensure_ascii=False, indent=4, separators=(',', ': ')))
After a successful call, you should see the following response. For more information about the response, see Dictionary Lookup
[
{
"examples": [
{
"sourcePrefix": "More than a match for any ",
"sourceSuffix": ".",
"sourceTerm": "shark",
"targetPrefix": "Más que un fósforo para cualquier ",
"targetSuffix": ".",
"targetTerm": "tiburón"
},
{
"sourcePrefix": "Same with the mega ",
"sourceSuffix": ", of course.",
"sourceTerm": "shark",
"targetPrefix": "Y con el mega ",
"targetSuffix": ", por supuesto.",
"targetTerm": "tiburón"
},
{
"sourcePrefix": "A ",
"sourceSuffix": " ate it.",
"sourceTerm": "shark",
"targetPrefix": "Te la ha comido un ",
"targetSuffix": ".",
"targetTerm": "tiburón"
}
],
"normalizedSource": "shark",
"normalizedTarget": "tiburón"
}
]
Troubleshooting
Common HTTP status codes
HTTP status code
Description
Possible reason
200
OK
The request was successful.
400
Bad Request
A required parameter is missing, empty, or null. Or, the value passed to either a required or optional parameter is invalid. A common issue is a header that is too long.
401
Unauthorized
The request is not authorized. Check to make sure your key or token is valid and in the correct region. See alsoAuthentication.
429
Too Many Requests
You have exceeded the quota or rate of requests allowed for your subscription.
502
Bad Gateway
Network or server-side issue. May also indicate invalid headers.
Java users
If you're encountering connection issues, it may be that your SSL certificate has expired. To resolve this issue, install the DigiCertGlobalRootG2.crt to your private store.