TECH

Integrate Google Translate API with Nodejs (TypeScript)

The article will walk you through the processes involved to integrate Google Cloud Translation - Basic (v2) API. Setup Google Cloud Project 1. Create

Hitesh Verma May 11, 2023 · 2 min. read

The article will walk you through the processes involved to integrate Google Cloud Translation - Basic (v2) API.

Photo by <a href="https://unsplash.com/@leookubo" target="_blank">Leonardo Toshiro Okubo</a> on <a href="https://unsplash.com" target="_blank">Unsplash</a>
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 :-)

Read next

Customized Calendar in Flutter

Hey, have you ever wanted a date-picker in your app but not in a dialog box? And you tried all the dart packages out there but cannot change their UIs

Hitesh Verma May 28, 2023 · 9 min read

Flutter: Custom Cupertino Date Picker

Hitesh Verma in TECH
May 28, 2023 · 6 min read

Flutter | Highlight searched text in results

Hitesh Verma in TECH
May 12, 2023 · 4 min read