Home > Uncategorized > Microsoft Translation #API using #Azure #CognitiveServices

Microsoft Translation #API using #Azure #CognitiveServices

When it comes to translation APIs, then Google translate is perhaps the first that comes to mind, but there is also Microsoft Azure translation API, under their cognitive Services umbrella.

Here is some simple code to implement the API, – I’ve omitted my API keys, and assuming you are using the WesternEurope (Ireland) endpoint.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 |
                                       SecurityProtocolType.Tls |
                                       SecurityProtocolType.Tls11 |
                                       SecurityProtocolType.Tls12; 

const string strUrl = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=es&from=en";
var wc = new WebClient();
wc.Headers["Ocp-Apim-Subscription-Key"] = key;
wc.Headers["Ocp-Apim-Subscription-Region"] = "westeurope";
wc.Encoding = Encoding.UTF8;
var jPost = new [] { new { Text = "Hello, what is your name?"}};
var strPost = JsonConvert.SerializeObject(jPost, Formatting.Indented);
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
var json = "";
try
{
    json = wc.UploadString(strUrl, "POST", strPost);
  
}
catch (WebException exception)
{
    string strResult = "";
    if (exception.Response != null)
    {
        var responseStream = exception.Response.GetResponseStream();
        if (responseStream != null)
        {
            using (var reader = new StreamReader(responseStream))
            {
                strResult = reader.ReadToEnd();
            }
        }
    }
    throw new Exception(strResult);
}

var jResponse = JArray.Parse(json);
var translation = jResponse.First["translations"].First["text"].ToString();

It also requires the Newtonsoft.JSON Nuget package.

Hope this is useful to someone.

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: