Introduction

In this article, we are going to learn how to translate text into multiple languages using one of the important Cognitive Services API called Microsoft Translate Text API ( One of the API in Language API ). It's a simple cloud-based machine translation service and obviously we can test through simple Rest API call. Microsoft is using a new standard for high-quality AI-powered machine translations known as Neural Machine Translation (NMT).

Interface

The "ITranslateText" contains one signature for translating text content based on the given input. So we have injected this interface in the ASP.NET Core "Startup.cs" class as a "AddTransient".

C#
Edit|Remove
using System.Threading.Tasks; 
 
namespace TranslateTextApp.Business_Layer.Interface 
{ 
    interface ITranslateText 
    { 
        Task<string> Translate(string uri, string text, string key); 
    } 
} 
Translator Text API Service

We can add the valid Translator Text API Subscription Key into the following code.

C#
Edit|Remove
using Newtonsoft.Json; 
using System; 
using System.Net.Http; 
using System.Text; 
using System.Threading.Tasks; 
using TranslateTextApp.Business_Layer.Interface; 
 
namespace TranslateTextApp.Business_Layer 
{ 
    public class TranslateTextService : ITranslateText 
    {/// <summary>/// Translate the given text in to selected language./// </summary>/// <param name="uri">Request uri</param>/// <param name="text">The text is given for translation</param>/// <param name="key">Subscription key</param>/// <returns></returns> 
        public async Task<string> Translate(string uri, string text, string key) 
        { 
            System.Object[] body = new System.Object[] {new{ Text = text }}; 
            var requestBody = JsonConvert.SerializeObject(body); 
             
            using (var client = new HttpClient()) 
            using (var request = new HttpRequestMessage()) 
            { 
                request.Method = HttpMethod.Post; 
                request.RequestUri = new Uri(uri); 
                request.Content = new StringContent(requestBody, Encoding.UTF8, "application/json"); 
                request.Headers.Add("Ocp-Apim-Subscription-Key", key); 
 
                var response = await client.SendAsync(request); 
                var responseBody = await response.Content.ReadAsStringAsync(); 
                dynamic result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented); 
                 
                return result; 
            }}}}

Output

The given text is translated into desired language listed in a drop-down list using Microsoft Translator API.


Reference

Summary

From this article we have learned translate a text(typed in english) in to different languages as per the API documentation using one of the important Cognitive Services API ( Translator Text API is a part of Language API ). I hope this article is useful for all Azure Cognitive Services API beginners.