Google APIs Node.js Client
The `googleapis` package is Google's officially supported Node.js client library for interacting with a wide range of Google APIs. It provides a unified interface for over 200 Google services, including non-GCP APIs like YouTube, Gmail, and Google Drive, as well as some Google Cloud Platform (GCP) services. The library currently stands at version 171.4.0 and sees frequent updates, typically driven by automated API definition generators for individual service modules, leading to regular minor and patch releases. Major version bumps often aggregate breaking changes across various underlying API modules. A key differentiator is its comprehensive coverage of all Google APIs, contrasting with the `@google-cloud/*` libraries which are purpose-built and idiomatic Node.js clients specifically for Google Cloud Platform services. While `googleapis` provides authentication support for OAuth 2.0, API Keys, and JWT tokens, it is explicitly in maintenance mode, meaning new features will not be added, and development prioritizes critical bug fixes and security issues. For new projects utilizing GCP services, Google strongly recommends using the actively developed `@google-cloud/*` client libraries, which often offer gRPC support for improved performance.
Common errors
-
Error: The API returned an error: Error: Not Found
cause The requested API version or resource does not exist, or the API is not enabled for your Google Cloud Project. This can happen if the API name or version is incorrect, or if the API is not publicly available or requires special access.fixVerify the API name and version against the Google APIs Explorer. Ensure the API is enabled in your Google Cloud Project's API Library. Check for any required scopes or specific access permissions. -
Error: invalid_grant
cause This error typically indicates an issue with authentication credentials, such as an expired refresh token, an invalid service account key, or insufficient permissions for the authenticated identity (user or service account).fixFor OAuth2, ensure your refresh token is valid or re-authorize the user. For service accounts, verify the JSON key file is correct, not expired, and the service account has the necessary IAM roles. For Application Default Credentials (ADC), ensure `gcloud auth application-default login` has been run or `GOOGLE_APPLICATION_CREDENTIALS` is correctly set and points to a valid service account key. -
TypeError: google.youtube is not a function
cause This usually means the specific API client (e.g., `youtube`) could not be loaded or is not being accessed correctly from the `google` object. This might occur if the API is not supported by the version of `googleapis` installed, or if there's a typo in the API name.fixCheck the exact API name and required version on the Google APIs Explorer. Ensure your `googleapis` package is up-to-date, or install the specific `@googleapis/<api-name>` submodule if using granular installations. If TypeScript, ensure your import statements and type definitions are correct. -
ERR_REQUIRE_ESM: require() of ES Module ... not supported
cause You are attempting to use `require()` to import an ES Module package (like `googleapis` in newer Node.js versions or certain submodules) in a CommonJS context without proper configuration. Node.js >=18 defaults to ESM.fixUpdate your code to use `import` statements: `import { google } from 'googleapis';`. Ensure your `package.json` has `"type": "module"` if you intend to write ESM, or configure a transpiler like Babel or TypeScript to output CommonJS if you must use `require()` with an ESM-only dependency.
Warnings
- gotcha For Google Cloud Platform (GCP) APIs (e.g., Cloud Storage, Pub/Sub, Datastore), it is strongly recommended to use the dedicated `@google-cloud/*` client libraries (e.g., `@google-cloud/storage`). These libraries are idiomatic, actively developed, often provide gRPC support for better performance, and are built specifically for GCP services. The `googleapis` library is in maintenance mode for new features, focusing on critical bugs and security updates, and is generally recommended for non-GCP Google APIs.
- breaking The `googleapis` package requires Node.js version 18 or greater. Older Node.js versions are not supported and may lead to installation failures or runtime errors.
- gotcha While API keys can be used for simple, public data access, more secure and recommended authentication methods for Google APIs, especially when accessing user data or sensitive resources, include OAuth 2.0 (user accounts), Service Accounts (server-to-server), and Application Default Credentials (ADC). Using static API keys or hardcoding credentials is a common security anti-pattern.
- gotcha To reduce application startup times and dependency footprint, you can install individual API modules as separate `@googleapis/*` submodules (e.g., `npm install @googleapis/docs`) instead of the monolithic `googleapis` package. This is particularly beneficial if you only interact with a few Google APIs.
- breaking Breaking changes for specific API modules are regularly introduced and are aggregated into major releases of the `googleapis` package. Always review the changelog for the specific API version you are using (e.g., `youtube-v3`) and the main `googleapis` package to understand potential impacts on your application.
Install
-
npm install googleapis -
yarn add googleapis -
pnpm add googleapis
Imports
- google
const google = require('googleapis');import { google } from 'googleapis'; - Auth.GoogleAuth
import { GoogleAuth } from 'googleapis/build/src/auth/googleauth';import { GoogleAuth } from 'google-auth-library'; - youtube_v3.Youtube
import { Youtube } from 'googleapis/build/src/apis/youtube/v3';import { youtube_v3 } from 'googleapis';
Quickstart
import { google } from 'googleapis';
async function getBlogDetails(blogId: string, apiKey: string) {
// Each API may support multiple versions. With this sample, we're getting
// v3 of the blogger API, and using an API key to authenticate.
const blogger = google.blogger({
version: 'v3',
auth: apiKey
});
const params = {
blogId: blogId
};
try {
// Get the blog details
const res = await blogger.blogs.get(params);
console.log(`Successfully retrieved blog ID: ${blogId}`);
console.log(`The blog URL is: ${res.data.url}`);
console.log(`Blog Title: ${res.data.name}`);
return res.data;
} catch (err) {
console.error('The API returned an error: ' + err);
throw err;
}
}
// To run this example, replace 'YOUR_BLOG_ID' and process.env.GOOGLE_API_KEY with actual values.
// A public blog ID can be found via Google APIs Explorer or your own Blogger account.
const BLOG_ID = process.env.BLOG_ID ?? '3213900'; // Example public blog ID
const API_KEY = process.env.GOOGLE_API_KEY ?? ''; // Ensure you have an API key enabled for Blogger API
if (!API_KEY) {
console.warn('Warning: No GOOGLE_API_KEY provided. This example might fail if the API requires authentication.');
}
getBlogDetails(BLOG_ID, API_KEY)
.then(details => console.log('Operation complete.'))
.catch(error => console.error('Failed to get blog details.', error));