DEV Community

Vikram Sharma
Vikram Sharma

Posted on

Google Translate API Tutorial

Google Translate is a powerful NLP language translation service. Formerly, it was available only as a web app to detect and translate between languages. However, Google Translate is now also available as an API. Google Translate API supports over a hundred languages.

An Overview of Google Translate API

The API is simple. It has two endpoints, “detect” and “translate”. As the name suggests, one is for language detection and the other is for translating from one language to another. It has a free quota limit of 50 API calls a day. Beyond that the cost os $0.05 per API call.

Test Drive!

Language Detection using Google Translate

The first endpoint is “detect”. Select the endpoint and hit the “Test Endpoint” button with the default inputs. The default input for the ‘q’ parameter is set to a text in English. The API response returns a JSON object with a key “language” whose value is set to ‘en’ which is the ISO 638 code for English. You can try the API by setting the ‘q’ parameter with any other language from the list of supported languages.

Language Translation using Google Translate

For translation, select the “translate” endpoint and choose the ‘q’ and ‘target’ parameter, as shown. As evident, you are translating the text “Hello, world!” into Japanese. Hit “Test Endpoint”, and you should see a response within a few seconds. You can verify the translated text contained in the “translatedText” key of the JSON response by feeding it into the Google Translate web app or any other online service. You can further explore the optional parameters defined for the “translate” endpoint.

Of particular interest is the ‘model’ parameter, which accepts a value of “base” (as default, also interpreted as blank value) or “nmt” to select the underlying machine learning model to use for translation. You can try translating the same text by using both the options to see which one results in more accurate translation.

Apart from that, you can specify the format of the input via the ‘format’ parameter. By default, you pass plain text for the ‘q’ parameter, as you have seen in the example above. However, you can also pass the value as ‘html’ to indicate an HTML input text. This is a nifty feature when you want to translate a scraped HTML document from the web. In this case, you directly pass the HTML formatted data from the HTML document instead of extracting the text from HTML and passing that as plain text.

The ‘source’ parameter specifies the source language, which is set to ‘en’ by default. Since the Google Translate API is pretty accurate at detecting the language, you hardly ever have to set this.

References

  1. Google Translate API Docs
  2. Google Translate Rakuten Rapid API Marketplace

Discussion (0)