aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
aster.cloud aster.cloud
  • /
  • Platforms
    • Public Cloud
    • On-Premise
    • Hybrid Cloud
    • Data
  • Architecture
    • Design
    • Solutions
    • Enterprise
  • Engineering
    • Automation
    • Software Engineering
    • Project Management
    • DevOps
  • Programming
    • Learning
  • Tools
  • About
code
  • Engineering
  • Practices

Using The Node.js Cloud Client Libraries

  • aster.cloud
  • July 5, 2022
  • 6 minute read

Beyond running your mission-critical serverless apps at global scale, Google Cloud provides a vast array of products that you can leverage to add valuable features to your apps. Use Node.js Cloud Client Libraries to reduce and simplify the amount of JavaScript or TypeScript code you need to write for accessing a product through its Application Programming Interface (API).

Problem

You want to create a Node.js service that uses a Google Cloud API.


Partner with aster.cloud
for your next big idea.
Let us know here.



From our partners:

CITI.IO :: Business. Institutions. Society. Global Political Economy.
CYBERPOGO.COM :: For the Arts, Sciences, and Technology.
DADAHACKS.COM :: Parenting For The Rest Of Us.
ZEDISTA.COM :: Entertainment. Sports. Culture. Escape.
TAKUMAKU.COM :: For The Hearth And Home.
ASTER.CLOUD :: From The Cloud And Beyond.
LIWAIWAI.COM :: Intelligence, Inside and Outside.
GLOBALCLOUDPLATFORMS.COM :: For The World's Computing Needs.
FIREGULAMAN.COM :: For The Fire In The Belly Of The Coder.
ASTERCASTER.COM :: Supra Astra. Beyond The Stars.
BARTDAY.COM :: Prosperity For Everyone.

Solution

Use the appropriate library from a list of more than a hundred available Node.js Cloud Client Libraries for connecting to a specific API.

Explanation

The Google Cloud Client Libraries team crafts libraries for Node.js to:

  • Efficiently handle low-level communication details (including authenticating API requests)
  • Provide an idiomatic and consistent “best-practices” JavaScript and TypeScript programming experience

Getting started

You can access a Cloud API with just a few lines of code using one of the Node.js Cloud Client Libraries. Each library for each Cloud API follows the same pattern for initialization.

1. Find the Cloud API you want to use

Start with the Node.js Cloud Client Libraries reference page to find the library for a specific API.

For this demo, use the Cloud Translation library. You can find the link in the Libraries table or in the left sidebar (shortened to “translate”) to navigate to the specific reference page.

2. Follow the first three steps in the Before you begin section

Each library reference page will have a Before you begin section. Here are the first three steps:

  1. Select or create a Cloud Platform project.
  2. Enable billing for your project (learn more about Google’s Free Tier).
  3. Enable the Cloud Translation API.

Skip step #4. We won’t cover local testing in this article.

3. Enable Cloud Build and Cloud Run APIs

Enable the following APIs to be able to build and store the container image for your app, and then run the app container on Cloud Run.

  1. Enable the Cloud Build API
  2. Enable the Artifact Registry API
  3. Enable the Cloud Run Admin API

 

 

Tip

You can find and enable Cloud APIs for your project on this console page.

 

4. Install the specific API client library

The library reference page tells you which library you need to install. For the Translate client enter the following:

npm install @google-cloud/translate

5. Add the client library to your code

const {Translate} = require(‘@google-cloud/translate’).v2;

Or using import syntax with TypeScript (or modern JavaScript modules support):

import {v2} from ‘@google-cloud/translate’;

const {Translate} = v2;

6. Use the client library

You’ll need the Project ID from the Google Cloud project you created above in Step 2.1. If you need to find it again, go to your cloud project dashboard.

Create an API client instance.

const projectId = ‘tpujals-node-client-demo’;

const client = new Translate({projectId});

Now you can invoke methods on the client. For the Translate client, there are a number of translate methods. Here’s a very simple translate method you can try:

const text = ‘Hello, world!’;

const targetLanguage = ‘ja’;

 

const [translation] = await client.translate(text, target);

console.log(`${text} => ${translation}`);

 

Tip

It might not be immediately obvious, but whenever you’re looking for reference documentation for different versions of clients and any related classes, go to the specific API reference page and look at the items under the expanded library selection in the left sidebar. Aside from Quickstart and Overview, the other items are the class documentation for each client version.

Cloud Translation is available in a Basic edition (v2) and an Advanced edition (v3). To demonstrate using the client library, we’re using the Basic edition. If you want to know more, see Compare Basic and Advanced.

 

As you can see from the reference documentation, the translate method returns a Promise (all of the client’s methods do) for obtaining a result asynchronously.

In this example, the result you’re interested in is the first element of a tuple (the translated string). You await completion of the promise and use destructuring assignment syntax to set the translation variable.

There are a number of things that can go wrong here (from being unable to connect, failing authentication, to passing bad arguments). For production code, you’ll want to wrap your calls in appropriate try/catch statements.

Launching the demo (Node.js + Express + Angular app deployed on Cloud Run)

After following the getting started steps in the previous section, you’re ready to launch the demo. This GitHub repo for the demo shows how to build an app that uses the Node.js client library for the Translation API.

The app backend (under src/server) is a Node.js server that uses the Express framework and the frontend (under src/client) is an Angular client.

The bulk of the application is standard boilerplate. The essential parts to understand are the following:

  • The Express server serves the user interface and also an API (/api/translate) for making translation requests. Aside from API request handling boilerplate, the translation code is essentially the same that was shown in the Getting started section.
  • The frontend implements an Angular service (translate.service.ts) used by the user interface to communicate with the backend to request translations. The frontend is served as a static Single Page Application (SPA) from the backend server’s public directory. Note the use of location.origin to build the actual URL for requesting a translation so that the app works whether served from localhost or Cloud Run.

The arguments posted from the frontend are the text and the target (language code) for translation. Depending on the response status, the response data contains the translation or an error message.

Translation request form

 

 

Translation request response

 

 

 

Clone the demo @repo

Using your terminal, clone the demo repo and then change directory into it.

git clone https://github.com/subfuzion/demo-nodejs-cloud-client.git

cd demo-nodejs-cloud-client

Build the Angular client

You only need to enter the following command if you modify the client UI. Otherwise, you can skip this step.

./scripts/ng-build

Deploy the service to Cloud Run

You need the Project ID, region, and service name that you want to use. For example, to deploy to demo-project in us-central1 to create a Cloud Run service called translate-demo, enter the following commands in your terminal:

export PROJECT=demo-project

export REGION=us-central1

export SERVICE=translate-demo

./scripts/run-deploy

 

You will be prompted to create an Artifact Registry for storing your app image:

Deploying from source requires an Artifact Registry Docker repository to store built containers. A repository named [cloud-run-source-deploy] in region

[us-central1] will be created.

 

Do you want to continue (Y/n)?

Answer Y (or just press Enter) to continue.

You should see output that looks something like this:

Building using Dockerfile and deploying container to Cloud Run service [translate-demo] in project [demo-project] region [us-central1]

✓ Building and deploying new service… Done.

✓ Uploading sources…

✓ Building Container…

Logs are available at

[https://console.cloud.google.com/cloud-build/builds/f9eeb697-…?project=…].

✓ Creating Revision…

✓ Routing traffic…

✓ Setting IAM Policy…
Done.

Service [translate-demo] revision [translate-demo-00001-pid] has been deployed and is serving 100 percent of traffic.

Service URL: https://translate-demo-ao23awv5ca-uc.a.run.app

 

The Service URL contains the link to the running app, where you should now be able to see it in action.

Are there other ways to access Google Cloud APIs?

Yes. However, using the appropriate library from the Node.js Cloud Client Libraries is the recommended way to access a Google Cloud API. A dedicated team at Google Cloud focuses on optimizing, testing, and maintaining these libraries.

These libraries can access Google Cloud APIs using gRPC under the hood for communication efficiency, while simplifying authentication and communication details. Most Cloud APIs offer significantly better performance in throughput and CPU usage over a gRPC interface. Accessing an API using gRPC can increase throughput per CPU by as much as a factor of ten compared to the standard REST API. Using the Node.js Cloud Client Libraries is the easiest way to leverage these peformance gains.

Google APIs Node.js Client

If you need to access an API not available as one of the supported Cloud Client Libraries (such as Maps or YouTube), then you might be able to use the Google APIs Node.js Client instead. This is an older (but still actively maintained) client that is auto-generated from Google API endpoint specifications (see Google APIs Explorer).

However, keep in mind that the Google APIs Node.js Client only supports communication over REST, not gRPC, interfaces. Furthermore, since the REST interface code is auto-generated, working with this client is generally not quite as intuitive or idiomatic as working with dedicated, hand-crafted Cloud Client Libraries.

Access Cloud APIs directly

You can write your own JSON over HTTP code to access the REST interface exposed by different Cloud APIs. For gRPC-enabled Cloud APIs, you can generate your own gRPC client using the API’s protocol buffers service definition (check the GitHub repository).

However, since Cloud APIs only accept secure requests using TLS encryption, you will be responsible for authenticating with Google and handling many of the low level communication details that are automatically handled for you by Cloud Client Libraries. See HTTP guidelines and gRPC Authentication for relevant details.

Summary

Node.js Cloud Client Libraries are tuned for performance and simplify underlying low level protocol, authentication, reliability, and error handling management.

 

Pro tip

Using the Node.js Cloud Client Libraries is a best practice for accessing Google Cloud APIs. They generally offer the best performance, while saving you coding time and effort.

 

Links

Node.js Cloud Client Libraries

Google Cloud samples browser

Demo source code

 

 

By: Tony Pujals (JavaScript Developer Advocate)
Source: Google Cloud Blog

Read More  Google Cloud Next 2019 | How to Make Enterprise Search More Effective with Google Cloud Search

For enquiries, product placements, sponsorships, and collaborations, connect with us at [email protected]. We'd love to hear from you!

Our humans need coffee too! Your support is highly appreciated, thank you!

aster.cloud

Related Topics
  • API
  • Cloud Run
  • Google Cloud
  • Google Cloud API
  • Node js
You May Also Like
View Post
  • Engineering
  • Technology

Guide: Our top four AI Hypercomputer use cases, reference architectures and tutorials

  • March 9, 2025
View Post
  • Computing
  • Engineering

Why a decades old architecture decision is impeding the power of AI computing

  • February 19, 2025
View Post
  • Engineering
  • Software Engineering

This Month in Julia World

  • January 17, 2025
View Post
  • Engineering
  • Software Engineering

Google Summer of Code 2025 is here!

  • January 17, 2025
View Post
  • Data
  • Engineering

Hiding in Plain Site: Attackers Sneaking Malware into Images on Websites

  • January 16, 2025
View Post
  • Computing
  • Design
  • Engineering
  • Technology

Here’s why it’s important to build long-term cryptographic resilience

  • December 24, 2024
IBM and Ferrari Premium Partner
View Post
  • Data
  • Engineering

IBM Selected as Official Fan Engagement and Data Analytics Partner for Scuderia Ferrari HP

  • November 7, 2024
View Post
  • Engineering

Transforming the Developer Experience for Every Engineering Role

  • July 14, 2024

Stay Connected!
LATEST
  • college-of-cardinals-2025 1
    The Definitive Who’s Who of the 2025 Papal Conclave
    • May 7, 2025
  • conclave-poster-black-smoke 2
    The World Is Revalidating Itself
    • May 6, 2025
  • 3
    Conclave: How A New Pope Is Chosen
    • April 25, 2025
  • Getting things done makes her feel amazing 4
    Nurturing Minds in the Digital Revolution
    • April 25, 2025
  • 5
    AI is automating our jobs – but values need to change if we are to be liberated by it
    • April 17, 2025
  • 6
    Canonical Releases Ubuntu 25.04 Plucky Puffin
    • April 17, 2025
  • 7
    United States Army Enterprise Cloud Management Agency Expands its Oracle Defense Cloud Services
    • April 15, 2025
  • 8
    Tokyo Electron and IBM Renew Collaboration for Advanced Semiconductor Technology
    • April 2, 2025
  • 9
    IBM Accelerates Momentum in the as a Service Space with Growing Portfolio of Tools Simplifying Infrastructure Management
    • March 27, 2025
  • 10
    Tariffs, Trump, and Other Things That Start With T – They’re Not The Problem, It’s How We Use Them
    • March 25, 2025
about
Hello World!

We are aster.cloud. We’re created by programmers for programmers.

Our site aims to provide guides, programming tips, reviews, and interesting materials for tech people and those who want to learn in general.

We would like to hear from you.

If you have any feedback, enquiries, or sponsorship request, kindly reach out to us at:

[email protected]
Most Popular
  • 1
    IBM contributes key open-source projects to Linux Foundation to advance AI community participation
    • March 22, 2025
  • 2
    Co-op mode: New partners driving the future of gaming with AI
    • March 22, 2025
  • 3
    Mitsubishi Motors Canada Launches AI-Powered “Intelligent Companion” to Transform the 2025 Outlander Buying Experience
    • March 10, 2025
  • PiPiPi 4
    The Unexpected Pi-Fect Deals This March 14
    • March 13, 2025
  • Nintendo Switch Deals on Amazon 5
    10 Physical Nintendo Switch Game Deals on MAR10 Day!
    • March 9, 2025
  • /
  • Technology
  • Tools
  • About
  • Contact Us

Input your search keywords and press Enter.