The article will walk you through the processes involved to integrate Google Cloud Translation - Basic (v2) API.
Photo by Leonardo Toshiro Okubo on Unsplash
Setup Google Cloud Project
1. Create a new project on Google Cloud Console or use an existing one.
2. Go to APIs & Services > Enable APIs & services > Search for Cloud Translation API & click enable.
3. Go to IAM & Admin > Service Accounts > Click on Create Sevice Account
a. Give a service account name in step 1, let’s say “Backend Server”.
b. Give the “Cloud Translation API Editor” role in step 2.
c. Skip step 3.
Click on the service account, go to "KEYS" tab, click on "ADD KEY" > Create new key > Select JSON format and then create. Save this JSON file.
Setup NodeJS Project
1. Create a new NodeJS project with TypeScript or use an existing one.
2. Install google-translate package npm i @google-cloud/translate
3. Save the downloaded service-account.json file to your project folder.
4. Set GOOGLE_APPLICATION_CREDENTIALS environment variable to the service-account.json file path in the index.ts file.
process.env.GOOGLE_APPLICATION_CREDENTIALS = "<path/to/service/account/json/file>";
5. Create a service class for translating an array of strings to the target language.
const { Translate } = require("@google-cloud/translate").v2; export class TranslationService { async translate(texts: string[], targetLang: string): Promise { let [translations] = await new Translate().translate(texts, targetLang); translations = Array.isArray(translations) ? translations : [translations]; return translations; } }
Thank you for reading this article. I hope it helped you :-)