Quickstart: Azure Cognitive Services Translator

In this quickstart, you'll get started using the Translator service to translate text with a programming language of your choice and the REST API.

Note

  • For this quickstart it is recommended that you use a Translator text single-service global resource.
  • With a single-service global resource you'll include one authorization header (Ocp-Apim-Subscription-key) with the REST API request. The value for Ocp-Apim-Subscription-key is your Azure secret key for your Translator Text subscription.
  • If you choose to use the multi-service Cognitive Services or regional Translator resource, two authentication headers will be required: (Ocp-Api-Subscription-Key and Ocp-Apim-Subscription-Region). The value for Ocp-Apim-Subscription-Region is the region associated with your subscription.
  • For more information on how to use the Ocp-Apim-Subscription-Region header, see Text Translator REST API headers.

Prerequisites

To get started, you'll need an active Azure subscription. If you don't have an Azure subscription, you can create one for free

  • Once you have your Azure subscription, create a Translator resource in the Azure portal.

  • After your resource deploys, select Go to resource and retrieve your key and endpoint.

    • You need the key and endpoint from the resource to connect your application to the Translator service. You'll paste your key and endpoint into the code later in the quickstart. You can find these values on the Azure portal Keys and Endpoint page:

      Screenshot: Azure portal keys and endpoint page.

  • Use the free pricing tier (F0) to try the service and upgrade later to a paid tier for production.

Headers

To call the Translator service via the REST API, you'll need to include the following headers with each request. Don't worry, we'll include the headers for you in the sample code for each programming language.

For more information on Translator authentication options, see the Translator v3 reference guide.

Header Value Condition
Ocp-Apim-Subscription-Key Your Translator service key from the Azure portal. Required
Ocp-Apim-Subscription-Region The region where your resource was created. Required when using a multi-service Cognitive Services or regional (non-global) resource.
Optional when using a single-service global Translator Resource.
Content-Type The content type of the payload. The accepted value is application/json or charset=UTF-8. Required
Content-Length The length of the request body. Optional

Important

Remember to remove the key from your code when you're done, and never post it publicly. For production, use a secure way of storing and accessing your credentials like Azure Key Vault. For more information, see the Cognitive Services security article.

Translate text

The core operation of the Translator service is translating text. In this quickstart, you'll build a request using a programming language of your choice that takes a single source (from) and provides two outputs (to). Then we'll review some parameters that can be used to adjust both the request and the response.

Set up your Visual Studio project

  1. Make sure you have the current version of Visual Studio IDE.

    Tip

    If you're new to Visual Studio, try the Introduction to Visual Studio Learn module.

  2. Open Visual Studio.

  3. On the Start page, choose Create a new project.

    Screenshot: Visual Studio start window.

  4. On the Create a new project page, enter console in the search box. Choose the Console Application template, then choose Next.

    Screenshot: Visual Studio's create new project page.

  5. In the Configure your new project dialog window, enter translator_quickstart in the Project name box. Leave the "Place solution and project in the same directory" checkbox unchecked and select Next.

    Screenshot: Visual Studio's configure new project dialog window.

  6. In the Additional information dialog window, make sure .NET 6.0 (Long-term support) is selected. Leave the "Don't use top-level statements" checkbox unchecked and select Create.

    Screenshot: Visual Studio's additional information dialog window.

Install the Newtonsoft.json package with NuGet

  1. Right-click on your translator_quickstart project and select Manage NuGet Packages... .

    Screenshot of the NuGet package search box.

  2. Select the Browse tab and type Newtonsoft.json.

    Screenshot of the NuGet package install window.

  3. Select install from the right package manager window to add the package to your project.

    Screenshot of the NuGet package install button.

Build your C# application

Note

  • Starting with .NET 6, new projects using the console template generate a new program style that differs from previous versions.
  • The new output uses recent C# features that simplify the code you need to write.
  • When you use the newer version, you only need to write the body of the Main method. You don't need to include top-level statements, global using directives, or implicit using directives.
  • For more information, see New C# templates generate top-level statements.
  1. Open the Program.cs file.

  2. Delete the pre-existing code, including the line Console.Writeline("Hello World!"). Copy and paste the code sample into your application's Program.cs file. Make sure you update the key variable with the value from your Azure portal Translator instance:

using System.Text;
using Newtonsoft.Json;

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=fr&to=zu";
        string textToTranslate = "I would really like to drive your car around the block a few times!";
        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);
        }
    }
}

Run your C# application

Once you've added a code sample to your application, choose the green start button next to formRecognizer_quickstart to build and run your program, or press F5.

Screenshot of the run program button in Visual Studio.

Translation output:

After a successful call, you should see the following response:

[
    {
        "detectedLanguage": {
            "language": "en",
            "score": 1.0
        },
        "translations": [
            {
                "text": "J'aimerais vraiment conduire votre voiture autour du pâté de maisons plusieurs fois!",
                "to": "fr"
            },
            {
                "text": "Ngingathanda ngempela ukushayela imoto yakho endaweni evimbelayo izikhathi ezimbalwa!",
                "to": "zu"
            }
        ]
    }
]

Next steps

That's it, congratulations! You've learned to use the Translator service to translate text.

Explore our how-to documentation and take a deeper dive into Translation service capabilities: