- Friction-free to get started – no installing stuff
- As little boiler-plate typing as possible – fill in the blanks and tweak rather than staring on a blank page and typing
We know what we’re going to use for the web page stuff:
- Hosting the web pages we’ll use CodePen – simple interface and easy sharing
- Writing HTML and CSS we’ll use the editor from HTML CheatSheets as a way to get started editing snippets of web code without needing so much typing
The next thing to sort out is how to make the basic call to the Google Translate API. We need something that hides the complexity of the API and leaves an interface something like:
translateFromTo("This original text", "english", "french");
Calling the Google Translate API
Google needs a few details to be covered off before you can actually use their translation API.
Google Cloud Account and API Key
You can’t just call the translate end point. You need to have a Google Cloud account set up and create an API key to access the translation service. You end up being on the hook for usage of the API key. The problem from the CoderDojo perspective is that all the attendees are going to need know the key, even if buried in a library, to be able to make translations. Here’s the plan:
- Lock the API usage down to specific IP addresses. All attendees are likely to be using the site wifi so presenting to Google as the same IP address. These are settings Google Cloud Console lets you change
- Put a reminder in my calendar to turn off the API once the dojo is over
Implementing the Library Function
Blocking Network Calls
translateFromTo() function to block the program execution until it synchronously returns a value. For synchronous HTTP requests out of the browser you need to turn to the old-school XMLHttpRequest and turn off the async flag when constructing a request with open().
Using the Google API Key
The other wrinkle to be aware of when implementing code that calls Google APIs is to pick the correct method for authenticating to the API service. The Google documentation tacitly makes the assumption that you’ll be using the OAuth service to get your users to authenticate through to Google before being allowed to use the API. This is not what we want for the CoderDojo. Rather, as described above, we want to use the simple API key. The use of the API key involves adding a
key= parameter to the request URL. The Google documentation for how to use the API in this mode is here.
Here’s the full code for the function:
Deploying Into CodePen
You can see the CodePen for yourself here: https://codepen.io/davepottssoftware/pen/dKNXaK