Call Azure Translator API to Get Supported Languages, Translate and Detect Language using C#

Translator is a cloud-based machine translation service you can use to translate text in near real-time through a simple REST API call. The service uses modern neural machine translation technology and offers statistical machine translation technology.

In this post, we will call three APIs. The first one is to get the list of all the Languages supported by the Translator. The second will be to translate text and the third one will detect language.

Prerequisites

  1. Valid Azure Subscription – Create a free Azure account here.
  2. Create Translator Resource in Azure Portal
  3. Visual Studio [Link Available in Downloads Page]

Create a Console App in Visual Studio

Open Visual Studio and click on Create a New Project. Search for Console Application and click on it.

Give a name of the project and choose a location.

Even though .NET 5.0 has come, we will go with .NET Core 3.1. Finally, click on Create.

We have the project ready. Let us start calling the APIs.

Get the Supported Language List

We have already covered calling all the three APIs using the Postman. We will just write C# code in this demo. Refer to my post on Calling Azure Translator API using Postman.

Below is the method which calls the API to get the list of Supported Language by Azure Translator.

private async Task GetSupportedLanguage(string uri)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, client.BaseAddress);
                
                var response = await MakeRequestAsync(request, client);
                Console.WriteLine(PrettyJson(response));
                
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new Exception();
            }
        }
public async Task<string> MakeRequestAsync(HttpRequestMessage getRequest, HttpClient client)
        {
            var response = await client.SendAsync(getRequest).ConfigureAwait(false);
            var responseString = string.Empty;
            try
            {
                response.EnsureSuccessStatusCode();
                responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            }
            catch (HttpRequestException)
            {
                // empty responseString
            }
            return responseString;
        }
        public string PrettyJson(string unPrettyJson)
        {
            var options = new JsonSerializerOptions()
            {
                WriteIndented = true
            };
            var jsonElement = System.Text.Json.JsonSerializer.Deserialize<JsonElement>(unPrettyJson);
            return System.Text.Json.JsonSerializer.Serialize(jsonElement, options);
        }

Output: This is just a sample of the output. The list is very long.

ESET Antivirus and Internet Security for Mac computers and laptops - Save 25%

Translate Text

Below is the method which takes the language code and the text to translate.

private async Task TranslateText(string toLanguage, string text)
        {
            string uri = "https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=" + toLanguage;
            
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<Your Key Here>");
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
                var body = $"[{{\"Text\": \"{text}\"}}]";
                var content = new StringContent(body, Encoding.UTF8, "application/json");
                request.Content = content;
                var response = await MakeRequestAsync(request, client);
                Console.WriteLine(PrettyJson(response));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new Exception();
            }
        }

Output:

Ad

Shop now for Get up to 20% off on AWS Certification Training,

Detect Language

Below is the method which takes the text and detects its language.

private async Task DetectLanguage(string text)
        {
            string uri = "https://api.cognitive.microsofttranslator.com/detect?api-version=3.0";
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(uri);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<Your Key Here>");
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);
                var body = $"[{{\"Text\": \"{text}\"}}]";
                var content = new StringContent(body, Encoding.UTF8, "application/json");
                request.Content = content;
                var response = await MakeRequestAsync(request, client);
                Console.WriteLine(PrettyJson(response));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new Exception();
            }
        }

Output:

Microsoft

Modify the Main Method

We call all the above methods from the Main.

static async Task Main(string[] args)
        {
            Program program = new Program();
            await program.GetSupportedLanguage("https://api.cognitive.microsofttranslator.com/languages?api-version=3.0&scope=translation");
            await program.TranslateText("it","Hello JD, How are you?");
            await program.DetectLanguage("Ciao JD, come stai?");
        }

Make sure to provide the Key present in the Translator resource in Azure.

Thank you All!!! Hope you find this useful.


Up ↑

%d bloggers like this: