Using Amazon Translate Api on Java

Sat, Jul 21, 2018 One-minute read

Adding translation to an application used to mean wrestling with dictionaries or third-party services of uneven quality. In this post I’ll show how to use the Amazon Translate API on Java with the AWS SDK to perform real-time translations instead.

Amazon Translate

Translate is a service that offers neural, accurate translation, and it’s friendly to get started with too, since the first 2 million “characters” per month are free. What we’ll do here is reach that service straight from our Java code.

The first thing to sort out is the Amazon dependency in our Maven configuration.

<dependencies>
        <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.371</version>
        </dependency>

    </dependencies>

With that available, the code itself is short. Here we translate English to Italian.

import com.amazonaws.services.translate.AmazonTranslate;
import com.amazonaws.services.translate.AmazonTranslateClient;
import com.amazonaws.services.translate.model.TranslateTextRequest;
import com.amazonaws.services.translate.model.TranslateTextResult;


public class TranslateApp {

    public static void main(String[] args) {
        AmazonTranslate translate = AmazonTranslateClient.builder()
                .withRegion("us-west-2")
                .build();

        TranslateTextRequest request = new TranslateTextRequest()
                .withText("Greetings from webischia :)")
                .withSourceLanguageCode("en")
                .withTargetLanguageCode("it");
        TranslateTextResult result  = translate.translateText(request);
        System.out.println(result.getTranslatedText());
    }
}

Running it, the response comes back as:

/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/bin/java... 
Saluti da webischia:)

Process finished with exit code 0

You can find the source code on GitHub.