using System.Text;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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=sw&to=it";
string textToTranslate = "Hello, friend! What did you do today?";
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);
// location required if you're using a multi-service or regional (not global) resource.
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-TRANSLATOR-KEY>"
endpoint := "https://api.cognitive.microsofttranslator.com/"
uri := endpoint + "/translate?api-version=3.0"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
location := "<YOUR-RESOURCE-LOCATION>"
// 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", "it")
q.Add("to", "sw")
u.RawQuery = q.Encode()
// Create an anonymous struct for your request body and encode it to JSON
body := []struct {
Text string
}{
{Text: "Hello friend! What did you do today?"},
}
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)
// location required if you're using a multi-service or regional (not global) resource.
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.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/translate?api-version=3.0&from=en&to=sw&to=it";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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, friend! What did you do today?\"}]");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText translateRequest = new TranslatorText();
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');
let key = "<your-translator-key>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
params.append("from", "en");
params.append("to", "sw");
params.append("to", "it");
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
data: [{
'text': 'Hello, friend! What did you do today?'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "<YOUR-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
location = "<YOUR-RESOURCE-LOCATION>"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'from': 'en',
'to': ['sw', 'it']
}
headers = {
'Ocp-Apim-Subscription-Key': key,
# location required if you're using a multi-service or regional (not global) resource.
'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, friend! What did you do today?'
}]
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=(',', ': ')))
呼び出しが成功すると、次の応答が表示されます。
[
{
"translations":[
{
"text":"Halo, rafiki! Ulifanya nini leo?",
"to":"sw"
},
{
"text":"Ciao, amico! Cosa hai fatto oggi?",
"to":"it"
}
]
}
]
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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=en&to=it";
string textToTranslate = "Halo, rafiki! Ulifanya nini leo?";
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");
// location required if you're using a multi-service or regional (not global) resource.
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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", "en")
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: "Halo rafiki! Ulifanya nini leo?"},
}
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)
// location required if you're using a multi-service or regional (not global) resource.
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.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/translate?api-version=3.0&to=en&to=it";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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\": \"Halo, rafiki! Ulifanya nini leo?\"}]");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText translateRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
params.append("to", "en");
params.append("to", "it");
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
data: [{
'text': 'Halo, rafiki! Ulifanya nini leo?'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "<YOUR-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
location = "<YOUR-RESOURCE-LOCATION>"
path = '/translate'
constructed_url = endpoint + path
params = {
'api-version': '3.0',
'to': ['en', 'it']
}
headers = {
'Ocp-Apim-Subscription-Key': key,
# location required if you're using a multi-service or regional (not global) resource.
'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': 'Halo, rafiki! Ulifanya nini leo?'
}]
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=(',', ': ')))
呼び出しが成功すると、次の応答が表示されます。
[
{
"detectedLanguage":{
"language":"sw",
"score":0.8
},
"translations":[
{
"text":"Hello friend! What did you do today?",
"to":"en"
},
{
"text":"Ciao amico! Cosa hai fatto oggi?",
"to":"it"
}
]
}
]
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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 = "Hallo Freund! Was hast du heute gemacht?";
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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: "Ciao amico! Cosa hai fatto oggi?"},
}
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)
// location required if you're using a multi-service or regional (not global) resource.
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.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/detect?api-version=3.0";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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\": \"Hallo Freund! Was hast du heute gemacht?\"}]");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText detectRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
axios({
baseURL: endpoint,
url: '/detect',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
data: [{
'text': 'Hallo Freund! Was hast du heute gemacht?'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "<YOUR-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
location = "<YOUR-RESOURCE-LOCATION>"
path = '/detect'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
# location required if you're using a multi-service or regional (not global) resource.
'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': 'Hallo Freund! Was hast du heute gemacht?'
}]
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=(',', ': ')))
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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, friend! What did you do today?";
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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, friend! What did you do today?"},
}
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)
// location required if you're using a multi-service or regional (not global) resource.
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.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/translate?api-version=3.0&to=th&toScript=latn";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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, friend! What did you do today?\"}]");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText translateRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
params.append("to", "th");
params.append("toScript", "latn");
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
data: [{
'text': 'Hello, friend! What did you do today?'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "<YOUR-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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,
# location required if you're using a multi-service or regional (not global) resource.
'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, friend! What did you do today?'
}]
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=(',', ': ')))
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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 = "/transliterate?api-version=3.0&language=th&fromScript=thai&toScript=latn";
string textToTransliterate = "สวัสดีเพื่อน! วันนี้คุณทำอะไร";
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);
// location required if you're using a multi-service or regional (not global) resource.
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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)
// location required if you're using a multi-service or regional (not global) resource.
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.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/transliterate?api-version=3.0&language=th&fromScript=thai&toScript=latn";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText transliterateRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
params.append("language", "th");
params.append("fromScript", "thai");
params.append("toScript", "latn");
axios({
baseURL: endpoint,
url: '/transliterate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
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-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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,
# location required if you're using a multi-service or regional (not global) resource.
'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=(',', ': ')))
呼び出しが成功すると、次の応答が表示されます。 translate エンドポイントの呼び出しとは異なり、transliterate では text と出力 script のみが返されます。
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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);
// location required if you're using a multi-service or regional (not global) resource.
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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)
// location required if you're using a multi-service or regional (not global) resource.
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.IOException;
import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/translate?api-version=3.0&to=es&includeSentenceLength=true";
public static String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText translateRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
params.append("to", "es");
params.append("includeSentenceLength", true);
axios({
baseURL: endpoint,
url: '/translate',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
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-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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,
# location required if you're using a multi-service or regional (not global) resource.
'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=(',', ': ')))
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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);
// location required if you're using a multi-service or regional (not global) resource.
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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)
// location required if you're using a multi-service or regional (not global) resource.
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 TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/breaksentence?api-version=3.0";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText breakSentenceRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
axios({
baseURL: endpoint,
url: '/breaksentence',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
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-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
location = "<YOUR-RESOURCE-LOCATION>"
path = '/breaksentence'
constructed_url = endpoint + path
params = {
'api-version': '3.0'
}
headers = {
'Ocp-Apim-Subscription-Key': key,
# location required if you're using a multi-service or regional (not global) resource.
'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=(',', ': ')))
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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 = "sunlight";
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);
// location required if you're using a multi-service or regional (not global) resource.
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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: "sunlight"},
}
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)
// location required if you're using a multi-service or regional (not global) resource.
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 TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/dictionary/lookup?api-version=3.0&from=en&to=es";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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\": \"sunlight\"}]");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText breakSentenceRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
params.append("from", "en");
params.append("to", "es");
axios({
baseURL: endpoint,
url: '/dictionary/lookup',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
data: [{
'text': 'sunlight'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "<YOUR-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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,
# location required if you're using a multi-service or regional (not global) resource.
'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': 'sunlight'
}]
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=(',', ': ')))
using System;
using Newtonsoft.Json; // Install Newtonsoft.Json with NuGet
class Program
{
private static readonly string key = "<YOUR-TRANSLATOR-KEY>";
private static readonly string endpoint = "https://api.cognitive.microsofttranslator.com";
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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 = "sunlight", Translation = "luz solar" } } ;
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);
// location required if you're using a multi-service or regional (not global) resource.
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-TRANSLATOR-KEY>"
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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: "sunlight",
Translation: "luz solar",
},
}
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)
// location required if you're using a multi-service or regional (not global) resource.
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 TranslatorText {
private static String key = "<YOUR-TRANSLATOR-KEY>";
public String endpoint = "https://api.cognitive.microsofttranslator.com";
public String route = "/dictionary/examples?api-version=3.0&from=en&to=es";
public String url = endpoint.concat(route);
// location, also known as region.
// required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
private static String location = "<YOUR-RESOURCE-LOCATION>";
// 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\": \"sunlight\", \"Translation\": \"luz solar\"}]");
Request request = new Request.Builder()
.url(url)
.post(body)
.addHeader("Ocp-Apim-Subscription-Key", key)
// location required if you're using a multi-service or regional (not global) resource.
.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 {
TranslatorText dictionaryExamplesRequest = new TranslatorText();
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');
let key = "<YOUR-TRANSLATOR-KEY>";
let endpoint = "https://api.cognitive.microsofttranslator.com";
// Add your location, also known as region. The default is global.
// This is required if using an Azure AI multi-service resource.
let location = "<YOUR-RESOURCE-LOCATION>";
let params = new URLSearchParams();
params.append("api-version", "3.0");
params.append("from", "en");
params.append("to", "es");
axios({
baseURL: endpoint,
url: '/dictionary/examples',
method: 'post',
headers: {
'Ocp-Apim-Subscription-Key': key,
// location required if you're using a multi-service or regional (not global) resource.
'Ocp-Apim-Subscription-Region': location,
'Content-type': 'application/json',
'X-ClientTraceId': uuidv4().toString()
},
params: params,
data: [{
'text': 'sunlight',
'translation': 'luz solar'
}],
responseType: 'json'
}).then(function(response){
console.log(JSON.stringify(response.data, null, 4));
})
import requests, uuid, json
# Add your key and endpoint
key = "<YOUR-TRANSLATOR-KEY>"
endpoint = "https://api.cognitive.microsofttranslator.com"
# location, also known as region.
# required if you're using a multi-service or regional (not global) resource. It can be found in the Azure portal on the Keys and Endpoint page.
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,
# location required if you're using a multi-service or regional (not global) resource.
'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': 'sunlight',
'translation': 'luz solar'
}]
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=(',', ': ')))
[
{
"normalizedSource":"sunlight",
"normalizedTarget":"luz solar",
"examples":[
{
"sourcePrefix":"You use a stake, silver, or ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"Se usa una estaca, plata, o ",
"targetTerm":"luz solar",
"targetSuffix":"."
},
{
"sourcePrefix":"A pocket of ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"Una bolsa de ",
"targetTerm":"luz solar",
"targetSuffix":"."
},
{
"sourcePrefix":"There must also be ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"También debe haber ",
"targetTerm":"luz solar",
"targetSuffix":"."
},
{
"sourcePrefix":"We were living off of current ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"Estábamos viviendo de la ",
"targetTerm":"luz solar",
"targetSuffix":" actual."
},
{
"sourcePrefix":"And they don't need unbroken ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"Y ellos no necesitan ",
"targetTerm":"luz solar",
"targetSuffix":" ininterrumpida."
},
{
"sourcePrefix":"We have lamps that give the exact equivalent of ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"Disponemos de lámparas que dan el equivalente exacto de ",
"targetTerm":"luz solar",
"targetSuffix":"."
},
{
"sourcePrefix":"Plants need water and ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"Las plantas necesitan agua y ",
"targetTerm":"luz solar",
"targetSuffix":"."
},
{
"sourcePrefix":"So this requires ",
"sourceTerm":"sunlight",
"sourceSuffix":".",
"targetPrefix":"Así que esto requiere ",
"targetTerm":"luz solar",
"targetSuffix":"."
},
{
"sourcePrefix":"And this pocket of ",
"sourceTerm":"sunlight",
"sourceSuffix":" freed humans from their ...",
"targetPrefix":"Y esta bolsa de ",
"targetTerm":"luz solar",
"targetSuffix":", liberó a los humanos de ..."
},
{
"sourcePrefix":"Since there is no ",
"sourceTerm":"sunlight",
"sourceSuffix":", the air within ...",
"targetPrefix":"Como no hay ",
"targetTerm":"luz solar",
"targetSuffix":", el aire atrapado en ..."
},
{
"sourcePrefix":"The ",
"sourceTerm":"sunlight",
"sourceSuffix":" shining through the glass creates a ...",
"targetPrefix":"La ",
"targetTerm":"luz solar",
"targetSuffix":" a través de la vidriera crea una ..."
},
{
"sourcePrefix":"Less ice reflects less ",
"sourceTerm":"sunlight",
"sourceSuffix":", and more open ocean ...",
"targetPrefix":"Menos hielo refleja menos ",
"targetTerm":"luz solar",
"targetSuffix":", y más mar abierto ..."
},
{
"sourcePrefix":"",
"sourceTerm":"Sunlight",
"sourceSuffix":" is most intense at midday, so ...",
"targetPrefix":"La ",
"targetTerm":"luz solar",
"targetSuffix":" es más intensa al mediodía, por lo que ..."
},
{
"sourcePrefix":"... capture huge amounts of ",
"sourceTerm":"sunlight",
"sourceSuffix":", so fueling their growth.",
"targetPrefix":"... capturan enormes cantidades de ",
"targetTerm":"luz solar",
"targetSuffix":" que favorecen su crecimiento."
},
{
"sourcePrefix":"... full height, giving more direct ",
"sourceTerm":"sunlight",
"sourceSuffix":" in the winter.",
"targetPrefix":"... altura completa, dando más ",
"targetTerm":"luz solar",
"targetSuffix":" directa durante el invierno."
}
]
}
]