Quickstart: Azure AI Translator REST APIs

Try the latest version of Azure AI Translator. In this quickstart, get started using the Translator service to translate text using a programming language of your choice or the REST API. For this project, we recommend using the free pricing tier (F0), while you're learning the technology, and later upgrading to a paid tier for production.

Prerequisites

You need an active Azure subscription. If you don't have an Azure subscription, you can create one for trial

  • 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 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.

      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 an Azure AI multi-service 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 Translation REST API headers.

Headers

To call the Translator service via the REST API, you need to include the following headers with each request. Don't worry, we 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 an Azure AI multi-service or regional (geographic) resource like China North.
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 Azure AI services security article.

Translate text

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

For detailed information regarding Azure AI Translator service request limits, see Text translation request limits.

Set up your Java environment

  • You should have the latest version of Visual Studio Code or your preferred IDE. See Java in Visual Studio Code.

    Tip

    • Visual Studio Code offers a Coding Pack for Java for Windows and macOS.The coding pack is a bundle of VS Code, the Java Development Kit (JDK), and a collection of suggested extensions by Microsoft. The Coding Pack can also be used to fix an existing development environment.
    • If you are using VS Code and the Coding Pack For Java, install the Gradle for Java extension.
  • If you aren't using Visual Studio Code, make sure you have the following installed in your development environment:

Create a new Gradle project

  1. In console window (such as cmd, PowerShell, or Bash), create a new directory for your app called translator-text-app, and navigate to it.

    mkdir translator-text-app && translator-text-app
    
     mkdir translator-text-app; cd translator-text-app
    
  2. Run the gradle init command from the translator-text-app directory. This command creates essential build files for Gradle, including build.gradle.kts, which is used at runtime to create and configure your application.

    gradle init --type basic
    
  3. When prompted to choose a DSL, select Kotlin.

  4. Accept the default project name (translator-text-app) by selecting Return or Enter.

  5. Update build.gradle.kts with the following code:

plugins {
  java
  application
}
application {
  mainClass.set("TranslatorText")
}
repositories {
  mavenCentral()
}
dependencies {
  implementation("com.squareup.okhttp3:okhttp:4.10.0")
  implementation("com.google.code.gson:gson:2.9.0")
}

Create your Java Application

  1. From the translator-text-app directory, run the following command:

    mkdir -p src/main/java
    

    You create the following directory structure:

    Screenshot: Java directory structure.

  2. Navigate to the java directory and create a file named TranslatorText.java.

    Tip

    • You can create a new file using PowerShell.

    • Open a PowerShell window in your project directory by holding down the Shift key and right-clicking the folder.

    • Type the following command New-Item TranslatorText.java.

    • You can also create a new file in your IDE named TranslatorText.java and save it to the java directory.

  3. Open the TranslatorText.java file in your IDE and copy then paste the following code sample into your application. Make sure you update the key with one of the key values from your Azure portal Translator instance:

import java.io.IOException;

import com.google.gson.*;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class TranslatorText {
    private static String key = "<your-translator-key";

    // 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 String location = "<YOUR-RESOURCE-LOCATION>";


    // Instantiates the OkHttpClient.
    OkHttpClient client = new OkHttpClient();

    // This function performs a POST request.
    public String Post() throws IOException {
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType,
                "[{\"Text\": \"I would really like to drive your car around the block a few times!\"}]");
        Request request = new Request.Builder()
                .url("https://api.translator.azure.cn/translate?api-version=3.0&from=en&to=fr&to=zu")
                .post(body)
                .addHeader("Ocp-Apim-Subscription-Key", key)
                // location required if you're using a multi-service or regional (not global) resource.
                .addHeader("Ocp-Apim-Subscription-Region", location)
                .addHeader("Content-type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    }

    // This function prettifies the json response.
    public static String prettify(String json_text) {
        JsonParser parser = new JsonParser();
        JsonElement json = parser.parse(json_text);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        return gson.toJson(json);
    }

    public static void main(String[] args) {
        try {
            TranslatorText translateRequest = new TranslatorText();
            String response = translateRequest.Post();
            System.out.println(prettify(response));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Build and run your Java application

Once you add a code sample to your application, navigate back to your main project directory—translator-text-app, open a console window, and enter the following commands:

  1. Build your application with the build command:

    gradle build
    
  2. Run your application with the run command:

    gradle run
    

Translation output:

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

[
  {
    "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 just learned to use the Translator service to translate text.

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