Перевод текста с помощью Google Translate API в Python
На самом деле вы можете многое сделать с помощью Google Translate API, начиная от определения языков и заканчивая простым переводом текста, настройкой исходного и целевого языков и переводом целых списков текстовых фраз. В этой статье вы узнаете, как работать с Google Translate API на языке программирования Python.
Установка Google Translate API
Прежде чем вы сможете работать с Google Translate API в Python, вам нужно будет установить его. Существует два разных способа установки API. Первый способ прост. Просто зайдите в терминал и используйте pip для установки API, как и для любой другой библиотеки Python. Для этого введите в своем терминале следующую команду:
Нажмите Enter и модуль Python для Google Translate API будет установлен в вашей системе.
Теперь, когда вы установили API, мы увидим его в действии с помощью нескольких примеров.
Список поддерживаемых языков
Google Translate API поддерживает множество языков. Чтобы вывести список всех поддерживаемых языков, запустите следующий скрипт:
При выполнении вышеприведенный фрагмент кода перечислит имена всех поддерживаемых языков вместе с их сокращенной записью. Вот как будет выглядеть вывод:
Основное использование
Давайте напечатаем все вышеперечисленные атрибуты и посмотрим, что мы получим
В приведенном выше примере мы не указали исходный язык. Поэтому Google Translate API пытается определить исходный язык. Аналогично, мы также не указали ни одного языка назначения, и поэтому API перевел исходный язык на язык по умолчанию, английский. Но что, если вы хотите указать исходный и целевой языки?
Указание исходного и целевого языков
На самом деле, очень легко указать язык назначения и исходный язык в Google Translate API. Вот код, который вы будете использовать для передачи только исходного языка:
Вы также можете передать исходный и целевой языки одновременно:
Давайте теперь переведем финское предложение на французский, а затем напечатаем исходный и целевой языки, а также переведенный текст. На этот раз мы укажем исходный и целевой языки.
Приведенный выше фрагмент кода даст следующий результат.
Перевод списка фраз
Давайте создадим список строк, содержащих некоторые фразы из французского языка.
Теперь пришло время вызвать метод translate() и передать в качестве параметров список, исходный язык и язык назначения.
Следующий результат будет отображаться на экране.
Перевод текстовых документов
Вы также можете проверить, находится ли файл в режиме «чтения», используя свойство mode :
Вот вывод содержимого файла:
Убедитесь, что у вас есть вышеуказанный контент в вашем текстовом файле, если вы хотите следовать нашему примеру.
Вывод должен выглядеть следующим образом:
Чтобы записать переведенный текст в тот же файл или другой текстовый файл, вы просто откроете файл в режиме записи («w»). Затем вам нужно вызвать метод write() и передать ему переведенный текст, как показано ниже:
В приведенном выше примере мы использовали менеджер контекста with для автоматического открытия и закрытия потока записи. Во-вторых, мы открыли файл в режиме записи. Наконец, мы использовали метод write() для записи переведенной строки в новый файл.
Вывод
Как получить и настроить ключ API Google для перевода в Wpgrabber?
В новой версии Wpgrabber 5.5 был внедрен автоматический перевод через сервис API Google Translate. В данной статье мы подробно опишем как получить сам ключ api для внедрения его в плагин.
1. Прежде всего Вам понадобится почта Гугла. Входим в ее аккаунт или, если почты нет — регистрируем новую по следующей ссылке:
РЕГИСТРАЦИЯ ПОЧТЫ
2. После того, как Вы вошли в почту и авторизировались, переходим по ссылке в Консоль облачной платформы.
При первом входе нужно поставить галочки и согласиться с условиями предоставления услуг, а также ПРАВИЛЬНО указать вашу страну. Это важно, потому как в дальнейшем придется привязывать карту и, если Вы не верно укажите фактическое место нахождения — возникнут проблемы:
3. Далее нажимаем вверху «Выберите проект» и в появившемся окне — «Создать новый проект»:
4. Называем свой новый проект любым именем, главное, чтоб буквы были на латинице, а в графе «Местоположение» оставляем все по умолчанию и нажимаем кнопку — «Создать»:
5. Далее нажимаем в левом верхнем углу Главная страница — Панель управления и далее клацаем по нашему созданному проекту:
и попадаем в саму панель:
6. Далее нужно привязать платежную карту. Сам ключ дается бесплатно и платить за него не нужно. По крайней мере в ближайший год, как пишут там — тестовый период. В дальнейшем можно снова брать ключ, но уже с другого аккаунта. Но привязать карту придется. Для привязки проще всего зайти в ваш онлайн-банкинг и выпустить виртуальную мгновенную карту. Лучше будет чтобы она не имела никакого отношения к основной, но тут уже по желанию.
Далее — Привязать платежный аккаунт — Создать платежный аккаунт:
7. В появившемся окне снова выбираем СВОЮ страну, соглашаемся с условиями и нажимаем — Далее:
8. Далее заполняем форму. На скриншоте — поля, отмеченные звездочкой заполняются реальными данными. Остальные — по усмотрению.
КРАЙНЕ ВАЖНО! Баланс добавляемой Вами карты в аккаунт должен быть не меньше 1$ по курсу валюты Вашей страны. Этот доллар снимется с карты для ее проверки, а потом деньги вернутся назад через несколько минут:
далее нажимаем — Начать бесплатный тестовый период и если все заполнили верно, появится вот такое окошко:
9.На этом активация Облака Гугл закончилась, переходим непосредственно к получению самого ключа API.
Для этого переходим вот по этой ссылке:
и нажимаем там — ВКЛЮЧИТЬ:
10. В выпадающем окне выбираем созданный Вами проект и нажимаем на него:
11. Далее переходим в Учетные данные:
и — Создать учетные данные Ключ API:
12. Ждем пару секунд и ключ наш создан:
13. Копируем его и идем в настройки плагина на Wpgrabber:
Во вкладке ПЕРЕВОДЫ ниже смотрим поле для API ключа Гугл, вставляем его в поле и ниже нажимаем — Сохранить изменения.
14. Теперь останется только в нужных лентах, которые будут работать через этот перевод — включить опцию Гугл-переводчика и выбрать направление перевода:
На этом настройка API ключа Гугл в плагин WPgrabber для автоматического перевода завершена. Ключ можно использовать сразу на нескольких ресурсах, но особо не увлекайтесь. Лучше получить несколько ключей с разных аккаунтов гугла.
How To Build Support for Language Translating In Web Forms (Google Translate API Tutorial) [JavaScript]
Last Updated on July 20, 2021 by Shyam Purkayastha 1 Comment
We are back with yet another tutorial on Google Translate API. This time we are going to address the language personalization feature on the web with this API.
As a non-native English speaker, if you come across a web form in English that you want to fill out and submit, it can be difficult to interpret the meaning of each form field. Using the Google Translate API, we can build language personalization features for web forms so that you can choose the language while filling out the form.
If this sounds interesting, then follow along this blog post to build a demo web form with language translation capability, powered by RapidAPI. But first, a very brief introduction to Google Translate API.
Is there a Google Translate API?
Google Translate needs no introduction. We all know about this popular service from Google, and you would have used it in the past via the Google Translate app. Under RapidAPI, you can work with the Google Translate API to call this service programmatically. Check out the API console to know more about the API.
A quick glance into the API endpoints tells us that it supports two endpoints.
POST Detect
The “POST Detect” endpoint returns the language code of the text string that is passed to API as input.
POST Translate
The “POST Translate” endpoint returns the translated text for a given input string that is passed to the API as input. Along with the input string, it also expects the language code of the translated language.
Is the Google Translate API Free?
How to get access to the Google Translate API? How to get an API Key?
1. Sign Up for Free RapidAPI Account
To begin using the Google Translate API, you’ll first need to sign up for a free RapidAPI developer account. With this account, you get a universal API Key to access all APIs hosted in RapidAPI.
RapidAPI is the world’s largest API marketplace, with over 10,000 APIs and a community of over 1,000,000 developers. Our goal is to help developers find and connect to APIs to help them build amazing apps.
2. Subscribe to Google Translate API
Once signed in, log in to your RapidAPI account and access the API console. Click on the “Pricing” tab and opt-in for the basic subscription that gives you 50 free API calls to Google Translate API per day.
3. Test Your API Subscription
Let’s test your Google Translate API subscription.
Select the “POST Translate” endpoint within the API console.
The default values of parameters indicate that we are going to translate the text “Hello, world!” to Spanish (with language code ‘es’).
Trigger the API, and you should see the translated text in the API response (JSON format).
So, “Hello, world!” in Spanish translates to “Hola Mundo!”.
If you want to try translating to other languages then you can check out the language codes defined as per the ISO 639 code definitions.
How To Use the Google Translate API with JavaScript: Build a Web Form with Translation Features
We now show you how to integrate this API into a web-based form. Be it a form hosted on a website or a mobile app. You can quickly integrate Google Translate into your front end code to provide language translation features.
Here is what a plain form looks like:
With some translation magic, here is how you can add some spark to it.
Follow the steps below to build a demo HTML page containing this form with a translation feature.
1. Create the Static HTML
We start with the bare-bones HTML page. The UI is based on Bootstrap and we add some CSS to spice up the form elements.
It also imports JQuery for performing all the UI operations that we describe subsequently.
2. Add Dropdown Click Handler
The main UI trigger for this page is the selection of language from the dropdown. Define a new
We will come back to this event handler and add the logic inside it.
3. Add JQuery AJAX Call To Invoke Google Translate API
You can get a code snippet for invoking the API from the API console of Google Translate API.
We define a global variable “settings” to contain the AJAX call parameters, with some modifications. And then add a new function to handle the AJAX call.
The value of the ‘target’ key for selecting the language will be set as part of the “click” event handler in step 6 below.
5. Add The Form Placeholder Update Code
The translated text returned by Google Translate API is deciphered based on the ‘|’ character and then replaced with the h1 tag as well as the placeholder text of the form elements. This happens inside another function updatePlaceholders( ) which is called as part of AJAX response handling.
6. Add Login for “click” Event Handler
Finally, we are ready to add some code inside the “click” event handler to complete the functionality.
By default the language is English. So the logic of the “click” event handler should decide to trigger the API only if the selected language is not English. Before triggering, it replaces the ‘target’ key under ‘settings.data’ with the language code of target language, that we embed as an HTML attribute to the dropdown menu element.
There you are. Now your form is capable of translating the placeholder text into three languages, Italian, Spanish and German. In case you want to get hold of the entire HTML file then here it is.
Translate On!
Google Translate API is quite handy for translating short text. However, in the case of longer text, it may not be very accurate. That’s why it is well suited for this kind of application that needs translation of short text consisting of a couple of words.
One more obvious thing to consider for this form is the repetition of API calls. As a smart coder, you would call the API once and cache the translated response, rather than calling it every time.
Take the existing code and give it a shot at optimizing the API calls. You would save a lot while developing an app that has a lot of dynamic forms to present to visitors from all across the world.
Other Applications
Good Luck! We will see you soon with yet another interesting API demo with RapidAPI.
Использование Google Translate API с PHP
Примечание: расширенное продолжение этой темы доступно здесь
Прочитав это руководство, вы сможете получать переводы из API Google Translate прямо из своего приложения. Вы узнаете, как получить доступ к API, как его использовать и как обрабатывать ошибки в случае их возникновения.
Создание аккаунта Google API
Чтобы получить доступ к API Google Translate, вам нужно будет создать новый проект в консоли API Google, для которого требуется активная учетная запись Google. После создания нового проекта просто включите Translate API в списке всех доступных API, нажав переключатель.
ценообразование
Если вы боитесь, что за переводы, которые вы делаете, будет выставлен слишком большой счет, вы можете контролировать использование API в своем проекте, устанавливая максимальное количество символов, которое можно переводить ежедневно. Вся конфигурация доступна на консоли API Google.
Получение ключа API
Доступ к Translate API из вашего приложения
Запрос образца
Перевод и обнаружение услуг платные, но мы можем использовать третий метод — языки — просто чтобы проверить, может ли наше приложение соединиться с API. Для этого мы сделаем запрос по следующему URL: https://www.googleapis.com/language/translate/v2/languages
Весь код выглядит следующим образом:
Получение переводов
Метод перевода имеет несколько параметров. Наиболее важными являются:
— q — ввод текста,
— source — исходный язык (если он не указан, Google попытается определить его автоматически),
— target — целевой язык
Если вы хотите получить переведенный текст, вы должны изменить URL-адрес запроса из предыдущего примера. Остальная часть кода выглядит очень похоже:
Пример ответа, содержащий переведенный текст, выглядит следующим образом:
Что произойдет, если вы не установите исходный язык?
Если вы решите не включать исходный язык (параметр источника ) в запрос, могут возникнуть два сценария:
1. Google удастся определить язык самостоятельно, поэтому ответ JSON будет содержать дополнительное свойство детектированное обнаружение ресурса, содержащее код исходного языка.
2. Исходный язык не будет успешно обнаружен (например, если исходный текст был слишком коротким), и Google Translate API вернет ошибку HTTP 500. Это приводит к следующей части урока — обработка ошибок.
Обработка ошибок
API Google Translate может возвращать следующие коды ошибок:
— 400 ( неверный запрос) — в вашем запросе отсутствуют некоторые параметры или вы передали неправильные значения параметрам, присутствующим в запросе (например, неверный код языка),
— 403 (запрещено) — вы ввели неверный ключ API или превысили квоту,
— 500 (Внутренняя ошибка сервера) — Google не может определить исходный язык вашего текста или произошла другая ошибка.
Кроме того, при возникновении ошибки API Google Translate возвращает ответ JSON, содержащий описание ошибки. Например, если один из обязательных параметров отсутствует, сервер ответит следующим ответом:
Поэтому лучший способ обработки ошибок при обращении к сервису API Google Translate — это просто совмещать проверку кода ответа HTTP и анализ ответа JSON с сервера. Что важно, curl_getinfo () должен быть вызван до curl_close () :
Несколько переводов в одном запросе
Также обратите внимание, что вы не можете получить несколько переводов одного исходного текста в одном запросе. Если вы хотите перевести один текст на разные целевые языки, вы должны сделать отдельные запросы.
Вывод
Теперь вы знаете основы подключения вашего приложения к Google Translate API. Более сложные реализации API могут включать автоматическую выборку переводов, когда пользователь отправляет некоторый контент (или когда администратор сайта одобряет это), и сохранение переводов в базе данных. Мы расскажем о таких продвинутых примерах в следующей статье (часть 2 здесь ).
Если вы планируете использовать API Google Translate в своем приложении, не забудьте прочитать Условия предоставления услуг и требования к атрибуции, которые содержат несколько рекомендаций о том, как отображать переведенный контент на веб-странице.
How to use Google Translate API in Java
Last Updated on September 14, 2020 by James Brannan Leave a Comment
Introduction
In this tutorial, we use the Google Translate API (version two) on RapidAPI using a Java command-line client. We program the client as a Spring Boot application and use three different Java REST libraries – the Eclipse Jersey implementation of the Java API for RESTful Web Services (JAX-RS), the Unirest-Java library, and the OkHttp library. Each library calls all three Google Translate endpoints – languages, detect, and translate. By the end of the tutorial, you will know how to use Java to get Google translate’s supported languages, identify a text’s language, and translate between two languages. But along the way, we will also model the application using the Unified Modeling Language (UML), use the Jackson library to serialize/deserialize JSON, and learn how to write a Spring Boot application as a console program rather than a web application.
RapidAPI
RapidAPI is an online repository of different REST APIs from many different sources. It provides a single location for the discovery and management of various REST APIs and provides a single source of registration and billing. RapidAPI started as a GitHub repository and has grown to over 10,000 APIs. RapidAPI does not host these APIs, but rather, provides a single location you can develop, manage, and access those disparate APIs. As more companies monetize their RESTful APIs, trying to discover those APIs and manage them becomes increasingly unwieldy. As a developer who works daily with REST APIs, and as a tutorial author for RapidAPI by night, I can personally attest that RapidAPI truly does offer a valuable service for developers needing to incorporate RESTful APIs into his or her application. See the following article on DZone for more arguments for RapidAPI (RapidAPI Provides API MarketPlace and Insight).
We do not discuss getting set up on RapidAPI here; however, here are some links to references needed to get started. Before continuing this tutorial, you should register for a RapidAPI account if you have not already.
Google Translate V2
Google’s Translate API is available on RapidAPI. The version on RapidAPI, as of the time of this tutorial, is version two. To use the API you must subscribe to it first, but don’t worry, the basic subscription is free. After subscribing, you should see the Test Endpoints button replace the Subscribe to Test button.

Endpoints
There are three exposed endpoints as of version two of the Google Translate API. The languages endpoint returns a list of languages supported by Google Translate, the detect endpoint detects the language of the specified text, and the translate endpoint translates text to a specified language. Let’s examine these three endpoints in more detail.
Languages
The languages endpoint returns a list of supported languages. It accepts a GET request that has two optional query string parameters, target and model. The endpoint returns a list of all supported languages, where the language value is the language code, and the name is the language’s name that was specified by the target query string parameter. If no target query string parameter is specified, then the name is omitted. The language’s code is the ISO 639-1 code (List of ISO 639-1 Codes). The target parameter’s value also uses a language’s ISO code. If the target language code is excluded, then the language names are omitted.
Let’s review the language endpoint by calling it and asking the results be returned in Chinese (Simplified). The request returns a list of language codes and names, as we specify the target language. After getting a list that includes names, we then exclude the target language from our request and obtain a list of language codes.
Detect Language
The detect endpoint takes a POST request with the text to analyze as a form field and returns the language it detects. Let’s use Chinese again, only this time as the language to detect.
RapidAPI Test Endpoint
Translate
The last endpoint to review is translate. The translate endpoint accepts a POST request and sends the text to translate as a form field. There are four form fields accepted by this endpoint:
RapidAPI Test Endpoint
Java Implementation: How do you use Google Translate API in your Java Application?
Now that we understand the three endpoints, we can write client Java code to call them. As mentioned in the introduction, here we use Spring Boot to develop our client application. There was no particular reason for my selecting Spring Boot, other than it is an easy way to free us from worrying about things such as project structure, creating a Maven pom file, and other tedious aspects involved in writing a non-trivial Java application. Because of this benefit of Spring Boot, we use it to develop a command-line application that runs directly in the JVM from the console and not in a web container. If you have never used Spring Boot to develop a console application, you will be surprised at how easy it is.
Modeling the Application
Call me crazy – or bitter that all my training in the Rational Unified Process seems for naught in an Agile world – but I always design an application before developing it, even if it is a tractable tutorial application. I don’t get the design perfect, but that’s okay, as all I need is something that helps guide my development. And so, let’s design the application before beginning to code, keeping in mind our agile intentions behind modeling.
Our modeling efforts consist of writing a use-case diagram, a class diagram, and an object model diagram. The notation we use is UML, and we use the online tool, yUML, to create our diagrams. Again, our goal is not a complete formalized representation of the system we will develop, but rather, an informal model using UML that serves as a “hand-written map” providing us directions to our destination.
Let’s begin by considering the interactions between a user and the application we will develop by creating a use-case model. The use-case model will help us see the interactions and their relationships more clearly.
Use Case Model
A use-case model illustrates how users will interact with a proposed system. It is useful for determining the requirements, or functionality, your system must perform. Let’s create a use-case model depicting the interactions users perform when interacting with our application. Of course, our application is a wrapper around the Google Translate API, so it might be more proper to state that we are creating a use-case diagram of a user’s interactions with the Google Translate API. But whatever we call our modeling subject, let’s model it.
Start by adding the user to the diagram. Of course, our application’s user is us, the developers, as we will be executing the application after developing it. And so we label the user as Developer. Our topmost interaction with our application is calling the Google Translate API. When we interact with the API, we call it using either the JAX-RS library, the Unirest-Java, or OkHttp library. As each sub-interaction is optional, we model these as extending the Call Google Translate interaction. But every call to Google Translate via RapidAPI, must include the RapidAPI required headers. As the getting RapidAPI headers interaction is required, we model this sub-interaction as being included by the Call Google Translate interaction.
When we interact with Google Translate using one of the three REST client libraries, we call all three REST endpoints. And so we model the languages, detect, and translate sub-interactions as included by the three REST library interactions. Now, we could have modeled each call as extending the REST library interaction. However, let’s assume that calling a REST library requires calling all three endpoints sequentially, and so we model them as being included. The following simple UML activity diagram illustrates our decision.

As our workflow illustrates, we conditionally call one of the three libraries to access the Google Translate API. We then use the selected library to call the languages, detect, and translate endpoints, respectively.
The use-case model provides a pretty good example of the user requirements our system must meet by having identified the user interactions with our proposed application. We can now create the following outline.
The outline furthers our understanding by providing a list of the functionality we must provide when we develop our application. Okay, now that we have a good understanding of the user interactions let’s focus on our application’s class design.
Application Class Diagram
A class diagram describes a system’s structure by illustrating its classes, their relationships, and their internal properties and methods. The diagram is especially useful when we first start coding our application, as we can create a bare-bones skeleton of our application derived from this model which we will then add functionality (functionality derived from the use-case model).
Note that the decision to create an abstract class extended by three concrete classes is a design decision; the decision is not the “correct” way to design our application. There are also good arguments for TutorialRestClient being an interface; however, let’s keep our design decision and make TutorialRestClient an abstract class.
Data Object Model
The REST endpoints return JSON resources from each of the three endpoints. When writing a Java application, it usually makes sense to convert these JSON string representations of a resource to a corresponding plain old Java object (POJO). One technique we can use to model these JSON resources as POJOs is by creating an Object Diagram that models the data objects an application will use as classes.
Return to the RapidAPI page and review the JSON returned from the three endpoints. Notice that all three endpoints wrap their particular JSON response with an opening and closing brace, thus defining an anonymous resource.

After defining the top-level resource, we identify the nested resource. Notice that all three endpoints also wraps its particular JSON resource in a data resource. And so, we define a Data object to represent the data resource.



The translate endpoint’s collection is named translations and contains anonymous resources that we call a Translation object.

We now determine the relationship between the resources. All three endpoints nest a data resource in the top-level anonymous resource; a GoogleTranslateObject is a collection of Data objects. Each endpoint contains a collection of its particular resource, and so we model each of the collections as an aggregation of the specific resource identified above. Note that there is an intermediate collection for the Detection resource (a collection of a collection of detection resources). We also add the properties of each JSON resource by listing the property name in the object.

We now translate the class diagram, combined with the object model and the outline from our use-case model, as our application’s skeleton; however, before we do, let’s return to Spring Boot and create our application’s foundation.
Project Setup
Navigate to the Spring Initializr web page and create our application. Through Spring Initializr, we define our classpath, add the project’s required dependencies, and set other settings needed by the application, such as if we will package the application as an executable Jar or as a War. Spring Initializr saves us considerable effort when creating our application by performing these tasks for us and providing a zip file containing our configured application.
Spring Initializr

Creating a project in Spring Initializr.
We now have the following pom file.
Spring Boot Application Class
Spring Boot Properties File
Now let’s modify the application.properties file to set our application’s properties. Adding these properties to the properties file allows us to use these values in our application without hard-coding them in our Java classes.
We now have the following application.properties file.
JSON Data Objects
Return to the model and let’s translate the object model we created earlier to create the needed data objects.
GoogleTranslateObject
We use the Jackson library to serialize and deserialize the data objects between JSON and POJOs. For Jackson to accomplish this task, it is essential to create the get
methods for every property present in the JSON resource.
Language
Now let’s create the Language data object.
Detection
The detection resource consists of a boolean value indicating if the detection is reliable, the detected language, and a confidence score. As an aside, it is my observation that Google Translate always guesses the language correctly, but invariably has little to no confidence in its translation ability (reliable is false, and the confidence score is low). Let’s finish the Detection class.
Translation
A Translation consists of the translated text and, if source language was not specified, the detected source language.
Component Classes
Now that we have the data objects coded let’s create the classes from our class diagram. Begin with the TutorialRestClient class.
TutorialRestClient Abstract Class
The TutorialRestClient class is abstract and declares three methods that call Google Translate’s three REST endpoints. The class also contains the shared headers and properties needed by the three child classes.
The class contains the three abstract methods we will override in the three child classes. The getSupportedLanguage and translate methods return a List aggregating the specific data objects, while the detectLanguage returns a nested list. TutorialRestClient also includes the properties we need using the Spring @Value annotation. Although this tutorial does not discuss Spring concepts in-depth, let’s pause to consider the @Value annotation.
@Value Annotation
JaxRsTutorialRestClientImpl Class
Before moving to individually developing the logic in each implementation class, let’s create all three classes and have the concrete methods overriding the abstract methods in TutorialRestClient return null values. We do this so so we don’t write a bunch of code all at once that doesn’t compile. Instead, we take baby-steps and make sure the application works each step of the way.
Let’s start with the JaxRsTutorialRestClientImpl class.
OkHttpTutorialRestClientImpl Class
UnirestTutorialRestClientImpl Class
Now that we have all three bare-bone classes let’s implement each class.
Endpoint Implementations
The first class we implement is the Eclipse Jersey implementation of the JAX-RS specification. We then code the class using the Unirest-Java library, followed by the class using the OkHttp library.
JAX-RS (JaxRsTutorialRestClientImpl)
As JAX-RS is the accepted standard with overwhelming industry support, we begin by implementing the endpoints in our JaxRsTutorialRestClientImpl class.
Languages (getSupportedLanguage)
Detect Language (detectLanguage)
Now let’s implement the detectLanguage method.
JAX-RS uses a Form object to represent an HTML form-data request. We add the text as a parameter to the Form instance and then use the Entity object to pass the form to the post request. When we post the form, we also specify that we expect the response to be a GoogleTranslateObject instance. We get the detections from the response and return the nested list of Detection instances.
Translate
Complete Class (JaxRsTutorialRestClientImpl)
The complete JaxRsTutorialRestClientImpl class follows.
TranslateClientApplication
Now we modify TranslateClientApplication to call our newly written class.
As you can see, developing a client using JAX-RS is straightforward. Moreover, it is the industry standard for working with RESTful web services when using Java. Because of this industry acceptance, JAX-RS is a safe bet when selecting a framework to write a REST client.
But there are situations when you might wish to use a different Java library. For instance, suppose you are writing an Android application. When using Android, a full-blown framework such as Eclipse Jersey, might prove overkill. In situations such as this, you might consider something lighter-weight such as Unirest-Java or OkHttp. And of course, as Unirest-Java and OkHttp are the two libraries used by RapidAPI as the Java examples on its website, let’s implement REST clients using these two libraries.
Unirest-Java (UnirestTutorialRestClientImpl)
Unirest-Java bills itself as a lightweight Http library for consuming RESTful APIs. Although smaller in size than a JAX-RS implementation, it remains a powerful library for writing REST clients.
Begin by adding the unirest-java and unirest-objectmapper-jackson libraries to the pom file.
Be careful when importing the classpath for Unirest-Java and OkHttp classes; be sure not to import a class from the wrong library.
The Unirest class is the entry point to the library. It is shared as a static class by all code in our class. We also statically add the JacksonObjectMapper and the default header to the class’s configuration. We can then use the configured Unirest class throughout the UnirestTutorialRestClientImpl class.
Languages (getSupportedLanguages)
The Unirest-Java API adds the headers, the get URL, the query string, and then executes the request in a single statement. Recall we set Jackson as the Unirest class’s ObjectMapper and so we can specify the response is a GoogleTranslateObject object instance. Unirest-Java then uses Jackson to translate the returned JSON string into the Java class. Note, had we preferred to set the headers all at once, we could have used a Map to pass the headers to the Unirest class.
Detect Language (detectLanguage)
Translate Language (translate)
Complete Class (UnirestTutorialRestClientImpl)
For convenience, the complete UnirestTutorialClientImpl class is included below.
TranslationClientApplication
You should obtain the following results printed to the console. Full disclosure, I executed the program within Eclipse. When using Microsoft Powershell, I could not get it to print the Chinese characters. You might have a similar problem running this from the command-line.
OkHttp (OkHttpTutorialRestClientImpl)
Let’s finish the tutorial by implementing the OkHttpTutorialRestClientImpl class using the OkHttp library.
As with the Unirest-Java library, we must first add the library to our application’s pom file.
Languages (getSupportedLanguages)
The OkHttpClient takes a Request instance, calls the newCall method to create a request and then executes that request using the execute method. It then uses the Jackson ObjectMapper instance to translate the response body to a GoogleTranslateObject instance and then obtains and returns the list of Language instances.
Detect Language (detectLanguage)
We start by creating an OkHttpClient instance and a RequestBody instance. We pass the inputString as a field to the RequestBody instance and then pass that to a Request instance. Finally, we call the OkHttpClient instance’s newCall method, passing the Request instance as a parameter. We then return the nested list of Detection instances.
Translate
Complete Class (OkHttpTutorialRestClientImpl)
The complete OkHttpTutorialRestClientImpl class follows.
TranslateClientApplication
Summary
In this tutorial, we used three different Java REST client libraries to call the three Google Translate REST endpoints. We first used the Eclipse Maven implementation of the JAX-RS standard. We then used the Unirest-Java and OkHttp lightweight REST client libraries. Before developing the application, we evaluated the Google Translate API’s REST endpoints and then modeled our application by creating a use-case diagram, class diagram, and object model diagram. We used the use-case diagram to create an outline of the tasks our application was to perform. We then used the models and outlines to develop our application. We implemented REST clients using JAX-RS, Unirest-Java, and OkHttp. Each client called all three of the Google Translate REST endpoints.
We covered a lot of material in this tutorial. Not only did we explore the three endpoints, we also explored how to write REST client, from analyzing the endpoints to modeling our application calling those endpoints, and then implementing the code. Hopefully you are convinced that preliminarily modeling even a simple REST client is not wasted effort. I truly believe it helps to understand immensely. You now have a better understanding of how to incorporate the Google Translate API on RapidAPI into your Java applications.



