Microsoft Translator API Example

Azure Cognitive Services Translator Text API C# Example

This Azure tutorial will discuss Azure Cognitive Services Translator Text API Examples.

Microsoft Translator API Example

In this article, We will discuss How to Translate Text Into Multiple Languages, Translator Text API With ASP.NET Core And C#. It is going to be an interesting article. As part of this article, we will perform the below steps

  • Create a Translator Text API in Azure Portal.
  • Create an ASP.NET Core application using Visual Studio 2019 and the Translator Text API Key.

Let’s discuss the Prerequisites needed for implementing the functionality here.

Prerequisites

Assuming you have all the prerequisites, Let’s start creating the Microsoft Translator Text API in the Azure Portal and discuss an Azure Cognitive Services Translator Text API Example.

Create a Microsoft Translator Text API in Azure Portal

The first step is creating an Azure Translator Text API in Azure Portal by following the below steps.

  1. Log in to the Azure Portal (https://portal.azure.com/)
  2. Once you log in to the Azure Portal, search for the Translator and then click on the search result Translator under the Marketplace as highlighted below.
Create a Microsoft Translator Text API in Azure Portal

Or, for the same option, you can click on the + Create a resource from the left navigation on the Home page. On the New window, search for the Translator and then click on the search result Translator.

Create a Translator Text API using Azure Portal

3. The next step is to click the Create button in the Translator window, as shown below.

How to Create a Microsoft Translator Text API in Azure Portal

4. Now, on the Create Translator window, Provide the below details

  • Subscription: You must Choose a valid subscription you want to use here.
  • Resource Group: You can choose your existing Resource Group here. If you haven’t had an existing Resource Group created, create a new Resource Group by clicking on the Create new link.
  • Resource Region: Select a Region for your Azure Resource.
  • Name: You must provide a unique name for your Azure Cognitive Services Translator Text API.
  • Pricing tier: You can select the Pricing tier based on your business needs. You can click on the View full pricing details link to verify the pricing details for your reference. For the Demo purpose, you can choose the Free F0 tier. For this tier, you can get up to 2M number of characters translated per month free of cost.

After providing all the above details, click on the Review + Create button as highlighted below.

Create a Microsoft Translator Text API using Azure Portal

5. On the next window, it will validate all the information entered by you on the above window, and then it will show you the Validation Passed message. You can see the Create button is enabled, as shown below. Now you can verify the details entered by you again for a safer side and then click on the Create button to create the Microsoft Translator Text API.

Create Microsoft Translator Text API Azure Portal

Once you click on the Create button, it will take a few seconds to create all the components, and you can see below the deployment is completed successfully without any issues. Click the Go to Resource button to see the Microsoft Translator Text API you created just now.

Create Microsoft Translator Text in API Azure Portal

Below is the Microsoft Translator Text API that we created just now.

Create Microsoft Translator Text API in Azure Portal

So, our Azure Cognitive Services Translator Text API is ready now. The next step is to copy the value of the Key1 of the Azure Cognitive Services Translator Text API. To copy the key1 value, click on the Keys and Endpoint option from the left navigation on the Cognitive Services window. You can click the Copy button to copy the Key1 or Key2 values as highlighted below. Copy the key value and keep it in a notepad that we will use in the Asp.Net core application code in Visual Studio.

Create Azure Cognitive Services Translator Text API

So, we have created the Azure Cognitive Services Translator Text API in Azure Portal and copied the key value of the Translator Text API, which we will use in the next steps.

Now is the time to create an Asp.Net core application using Visual Studio 2019.

Open Visual Studio 2019 and click on the Create a New Project button on the Getting Started page

Now, in the next window, choose the project template as ASP.Net Core Web Application and click the Next button.

Translate Text Into Multiple Languages Using Translator Text API

On the Configure your new project window, Provide the below details

  • Project Name: Provide a unique name for your Project.
  • Location: Choose a location where you want to save your project locally.

Then click on the Create button to navigate to the next window.

Create a Microsoft Translator Text API Azure Portal

On the Create a new ASP.NET Core web application window, select the web Application project template and click the Create button to create the project.

Create a Microsoft Translator Text API

Now, the Project will be created successfully without any issue

Now, we need to add the code needed for the functionality. It would be best if you did the below changes in the Index.cshtml file.

Azure Cognitive Services Translator Text API example

Now, you need to add the code for the site.js file below

$(function () {
    $(document)
        .on('change', '#ddlLCode', function () {
            var langCode = $(this).val();
            var eText = $("#idText").val();
            if (1 <= $("#idText").val().trim().length && languageCode != "NA") {

                $('#idText').removeClass('redBorder');

                var url = '/Home/Index';
                var dataToSend = { "LanguageCode": langCode, "Text": eText };
                dataType: "json",
                    $.ajax({
                        url: url,
                        data: dataToSend,
                        type: 'POST',
                        success: function (response) {
                           
                            var result = JSON.parse(response);
                            var tText = result[0].translations[0].text;
                            $('#idtransText').val(tText);
                        }
                    })
            }
            else {
                $('#idText').addClass('redBorder');
                $('#idtransText').val("");
            }
        });
});  

Now, the next steps are to create the interface named ITextTranslation which should contain the below lines of code

namespace DemoTranslateAPP
{
    interface ITextTranslation
    {
        Task<string> Translation(string uri, string text, string key);
    }
}

Now, the next is to create the TextTranslationService, which should contain the below code

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace DemoTranslateAPP
{
    public class TextTranslationService : ITextTranslation
    {
        public async Task<string> Translation(string uri, string text, string key)
        {
            System.Object[] body = new System.Object[] { new { Text = text } };
            var requestBody = JsonConvert.SerializeObject(body);

            using (var cnt = new HttpClient())
            using (var rqst = new HttpRequestMessage())
            {
                rqst.Method = HttpMethod.Post;
                rqst.RequestUri = new Uri(uri);
                rqst.Content = new StringContent(requestBody, Encoding.UTF8, "application/json");
                rqst.Headers.Add("Ocp-Apim-Subscription-Key", key);

                var rspns = await cnt.SendAsync(rqst);
                var responseBody = await rspns.Content.ReadAsStringAsync();
                dynamic result = JsonConvert.SerializeObject(JsonConvert.DeserializeObject(responseBody), Formatting.Indented);

                return result;
            }
        }
    }
}

Note: Don’t forget to inject the TextTranslationService and ITextTranslation in the startup.cs class file.

Now we are done with the changes, press F5 to run the project. Now, the project should run successfully without any issues.

The JSON response will be something like below

[  
  {  
    "detectedLanguage": {  
      "language": "en",  
      "score": 1.0  
    },  
    "translations": [  
      {  
        "text": "भगवान आपका भला करे",  
        "to": "God is Great"  
      }  
    ]  
  }  
]  

Enter the text and the text will get transferred to the language in the drop-down list.

This is how you can work with Azure Cognitive Services Translator Text API ASP.NET Core. We have discussed one of the Azure Cognitive Services Translator Text API Examples.

Example-2

Well, here we will discuss another example of implementing Azure Cognitive Services Translator Text API. Here, in this example, we will perform the below steps

  • We will create an Azure Cognitive Services Translator Text API in the Azure Portal
  • We will create a console application and use the Translator Text API there.

How To Create a Microsoft Translator Text API Using Azure Portal

The first step is to create a Microsoft Translator Text API Using Azure Portal. Since we have already created the Microsoft Translator Text API using the Azure Portal above. You can refer to the Create a Microsoft Translator Text API in the Azure Portal section of the article to create the Microsoft Translator Text API.

So, I will use the same Azure Cognitive Services Translator Text API I created above. Below is the Translator Text API that I have already created.

So, copy the Key1 value to a notepad we will use in the console application, which we will create in the next step. Click on the Copy button next to the Key1 value as highlighted below. You can also click on the Regenerate key1 or Regenerate key2 and copy the new key value if you want to use the new key value.

How To Create a Microsoft Translator Text API Using Azure Portal

We have copied the Key value of our Azure Translator Text API, and the Region for our Azure Translator Text API is eastus. Now, let’s move to the next step: creating a console application using Visual Studio 2019.

Create a console application using Visual Studio 2019

Follow the below steps to Create a console application using Visual Studio 2019.

Open the Visual Studio 2019 in your dev machine and click the Create a new project button in the Getting Started window.

Choose the Project template as Console App (.NET Framework) and click the Next Button. You can also select the Core Console App.

Create a Azure Translator Text API Azure Portal

Now, on the Configure your new project window, Provide the Project name, Choose a location for your Console application project, and then choose the Framework as the latest version of the .NET Framework. Finally, click the Create button to create the Console application.

How To Create a Microsoft Translator Text API

Now, the Project will be created successfully without any issues.

Now, the next step is to add the NuGet Package, i.e., Newtonsoft.Json, to the project. To add the NuGet package, Right-click on the Project and choose Manage NuGet Packages.

From the below window, select the Browse tab, search for Network.json, select the NuGet package, and click on the Install button to install the NuGet package as highlighted below.

Microsoft Translator Text API Example

Now, on the Program.cs file, add the below using statement

using Newtonsoft.Json;

Now, on the same Program.cs file. Add the rest of the code as below. Below is the complete code for the Program.cs file.

Note: Make sure to change the value for the Key-Value(Put the key value of your Azure Translator Text API that you have copied in the above step ) and then also change the value for the Ocp-Apim-Subscription-Region value (This should be the Region for your Azure Translator Text API. For me, it is eastus).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Newtonsoft.Json;



namespace DemoTranslatorAPI
{
    
   public class Program
    {
        private const string key = "db0746e18e27457fbe3ed52ba6188753";

        public static async Task Main()

        {
            while (true)
            {
                var text = Console.ReadLine();

                var lang = Console.ReadLine();
                Translate(text, lang);
            }
        }
        public static async void Translate(string text, string language)
        {
            var encodtxt = WebUtility.UrlEncode(text);
            string texttotranslate = text;

            string uri = $"https://api.cognitive.microsofttranslator.com//translate?api-version=3.0&from=en&to={language}";

            System.Object[] body = new System.Object[] { new { Text = texttotranslate } };
            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);
                request.Headers.Add("Ocp-Apim-Subscription-Region", "eastus");
                var response = await client.SendAsync(request);
                var responseBody = await response.Content.ReadAsStringAsync();

                var result = JsonConvert.DeserializeObject<List<Dictionary<string, List<Dictionary<string, string>>>>>(responseBody);
                var translation = result[0]["translations"][0]["text"];

                Console.WriteLine(translation);

            }
        }
    }
}

Now we are done with the code changes, Press F5 to run the Application. You can see the Console window. Type a word or sentence in English, choose the language code to translate the text, and press Enter from your keyboard.

For example, I entered the word “love” then chose “it”(Italian), and then pressed Enter. I entered a statement in English, “God bless you,” and then entered “it”(Italian), then pressed Enter from the Keyboard. Then I entered “God bless you,” and then entered “es,” and then I entered “love,” and then “es.” You can see I got the output below.

love
it
Amore
God Bless you
it
Dio ti benedica
God Bless you
es
Que dios te bendiga
love
es
Amor

You can see the Output below

How To Create a Microsoft Translator Text API Using Azure Portal

So, We have discussed here two Azure Cognitive Services Translator Text API Examples. One is with the ASP.Net core and one with the Console application. We discussed how to Translate Text Into Multiple Languages Using Translator Text API.

FAQs

What is Azure Cognitive Services Translator Text API?

The Translator Text API is a part of Azure Cognitive Services, a Microsoft AI service that helps you translate text to multiple languages easily. Azure Cognitive Services Translator Text API supports more than 70 languages for translation.

The Azure Cognitive Services Translator Text API has some key benefits. Those are as below

  • It supports more than 70 languages which is the biggest advantage.
  • You can build custom models for the translation based on your business-specific requirements.
  • As security plays an important role, it provides Built-in security for your Data. Your Data is safe.

We have a few ideas now on the Microsoft Translator Text API. Now

You may also like following the below Articles

Wrapping Up

Well, in this article, we have discussed Azure Cognitive Services Translator Text API ASP.NET Core Example. I hope you have enjoyed this article !!!