JavaScript Functional Google Translate API to translate JSON values.

Mateusz Wojczal
Escolasoft
Published in
5 min readJan 16, 2020

Google Translate is a service that allows you to automate translation from one language into another. It does translate not single terms but whole sentences as well. You can use it though the dedicated website but it also exposes API that can be used in bespoke applications.

Google Translate website service

In order to use to API you need to get the API access key which in case of this particular service is not as straight forward as in case of other Google APIs like Google Maps.

In this article I’ll try to cover two topics:

  1. Getting the Bearer token required to call the Google Translate API
  2. Using Google Translate API in JavaScript functional programming paradigm

Please note that first part of the tutorial covers only Linux and MacOs. There are some differences on Windows like installing SDK or setting environment variables.

Before we can start coding we need to get the token that will be used with every API call in our code. The steps below are also described in Quickstart but I’ll try to explain this easier. Later I’ll explain how to write a simple Node.JS script that will take JSON file as input and write another JSON file as output, so example file with polish terms like in the following snippet

{
"username": "Login",
"password": "Hasło",
"fullname": "Imię i Nazwisko"
}

might be translated into german

{
"username": "Einloggen",
"password": "Kennwort",
"fullname": "Vor- und Nachname"
}

Getting the Service Key

  1. Login or create an account in Google Developer Console
  2. Create or select a project.
  3. Enable the Cloud Translation API for that project.
  4. Create a service account.

5. Download a private key as JSON.

6. Once you save that on you disk copy to clipboard the absolute path to it. In my case this file path is/Users/qunabu/Downloads/project-ad1f87bcae9e.json

Install Google SDK

  1. Download https://cloud.google.com/sdk/docs/ and follow the instruction on Google SDK download page.
  2. Run the installation script ./google-cloud-sdk/install.sh from the folder where SDK was extracted.
  3. After installation restart the shell and run command gcloud auth application-default print-access-token that should fail at this stage and ask for GOOGLE_APPLICATION_CREDENTIALS which is suppose to be path to key generated in the previous stage.
  4. Set the path to key by setting environmental variable with export GOOGLE_APPLICATION_CREDENTIALS=/Users/qunabu/Downloads/project-ad1f87bcae9e.json
  5. At this stage gcloud auth application-default print-access-token should return that Token that is needed to the application. Please note that this token is valid only for a limited short period of time.

Writing the translation script.

Our application will be based functional programming paradigm in JavaScript language which is a huge topic. In this article I’m going to focus on

  • Pure functions which return value is only determined by its input values, without observable side effects and the always return the same results on particular input
  • No need to global variables and Immutability. We don’t change values we create new ones. Variables are passed as function arguments.
  • Chaining which is a technique used to simplify code where multiple methods are applied to an object one after another.

My code is going to perform single task — convert one object of language terms into translated ones.

Automated translation from polish to german.

Our first function is going to connect to Translation API and with support of fetch and Promise resolve translated term or reject if fails.

// GKEY is key generated  `gcloud auth application-default print-access-token`getTranslation({fullName:"Full Name"}, 'de', GKEY)
.then(response => console.log(response)) // returns {fullName:"Vollständiger Name"}
.catch(err => console.log(err)) // called in case of any error

Is this function pure? Actually it’s not because it does connect to API and side effect occurs — for instance with the same arguments like getTranslation({fullName:”Full Name”}, ‘de’, GKEY) can return different results because GKEY lifespan is short and is valid only for couple of minutes so the results is not always the same. Functions that depends on the environment is not pure but it’s nature — for instance API calls depends on the network connection

Please note the setTimeout exists in function because there is limited amount of simultaneous calls to API, so the function is calling it each 50 milliseconds.

Once we have function that actually translates the terms let’s create one that takes the key-value dictionary object and row by row translate them by calling getTranslation. Before that I would like to introduce two helpers functions that are going to be used.

Are convertToArray and convertToObject pure functions? Both of them do not mutate input data, have no side effect and for given inputs they always return the same results. Yes, they are pure, and they are based on Array methods map and reduce which are pure as well.

Now the function that process whole object row by row is below

Because it is related to getTranslation is not pure. Please note the recurrency which is one of the techniques often used in functional programming.

To see the final application code we need to include one more function:

which just loads an JSON file from local drive.

The final code of the app is below. It does use chaining technique from functional programming as well as method of catching errors without using throw/catch. convertToArray and convertToObject are not essential but its much easier to operate on the array cell by cell then on the pure object itself. The algorithm is straight forward:

  • load and parse JSON from local files
  • convert object to array
  • process whole array row by row and return new array with translated terms
  • convert array to object
  • save object to new JSON file
  • in case of any of above steps fails, stop and show an error

If you would like to play with the code the whole application is available on github.

Example of translating terms from polish to english with the script:

Example of running the app in the console.

--

--

Mateusz Wojczal
Escolasoft

founder of Qunabu Interactive from Gdańsk, Poland. Full-stack web developer with over a dozen years of experience.