Security News
cURL Project and Go Security Teams Reject CVSS as Broken
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
googleapis
Advanced tools
The googleapis npm package is a client library for accessing various Google APIs. It provides an easy way to integrate Google services into applications, allowing developers to interact with a wide range of Google services, including Google Drive, Gmail, Google Calendar, YouTube, and many more.
Google Drive API
This code sample demonstrates how to list files in a user's Google Drive using the Google Drive API.
const { google } = require('googleapis');
const drive = google.drive({ version: 'v3', auth });
// List files in Google Drive
drive.files.list({}, (err, res) => {
if (err) throw err;
const files = res.data.files;
if (files.length) {
console.log('Files:');
files.map((file) => {
console.log(`${file.name} (${file.id})`);
});
} else {
console.log('No files found.');
}
});
Gmail API
This code sample shows how to send an email using the Gmail API.
const { google } = require('googleapis');
const gmail = google.gmail({ version: 'v1', auth });
// Send an email using the Gmail API
gmail.users.messages.send({
userId: 'me',
requestBody: {
raw: emailMessage
}
}, (err, res) => {
if (err) throw err;
console.log('Email sent:', res.data);
});
Google Calendar API
This code sample illustrates how to create a new event in a user's Google Calendar.
const { google } = require('googleapis');
const calendar = google.calendar({ version: 'v3', auth });
// Insert a new calendar event
calendar.events.insert({
calendarId: 'primary',
resource: event,
}, (err, event) => {
if (err) throw err;
console.log('Event created: %s', event.htmlLink);
});
YouTube API
This code sample demonstrates how to search for videos on YouTube using the YouTube API.
const { google } = require('googleapis');
const youtube = google.youtube({ version: 'v3', auth });
// Search for videos on YouTube
youtube.search.list({
part: 'snippet',
q: 'Node.js on Google Cloud',
maxResults: 10
}, (err, response) => {
if (err) throw err;
const videos = response.data.items;
if (videos.length) {
console.log('Search results:');
videos.forEach((video) => {
console.log(`${video.snippet.title}`);
});
} else {
console.log('No search results found.');
}
});
The aws-sdk package is a client library for Amazon Web Services (AWS). It allows developers to interact with a wide range of AWS services such as Amazon S3, EC2, DynamoDB, and more. While it serves a similar purpose for AWS as googleapis does for Google services, the two are for different ecosystems.
google-api-nodejs-client
is Google's officially supported
node.js client
library for accessing Google APIs, it also supports authorization and
authentication with OAuth 2.0.
Note: This library is currently in alpha status, meaning that we can make changes in the future that may not be compatible with the previous versions.
The library is distributed on npm
. In order to add it as a dependency,
run the following command:
$ npm install googleapis
Dynamically load Google APIs and start making requests:
var googleapis = require('googleapis');
googleapis
.discover('urlshortener', 'v1')
.discover('plus', 'v3')
.execute(function(err, client) {
var params = { shortUrl: 'http://goo.gl/DdUKX' };
var req1 = client.urlshortener.url.get(params);
req1.execute(function (err, response) {
console.log('Long url is', response.longUrl);
});
var req2 = client.plus.people.get({ userId: '+BurcuDogan' });
req2.execute();
});
Supported APIs are listed on Google APIs Explorer.
Discovery documents are being cached for 5 minutes locally.
You can configure the directory used to store cached discovery
files by using the cache.path
option.
googleapis
.discover('plus', 'v3')
.withOpts({ cache: { path: '<path>' }))
.execute();
Client libraries are generated during runtime by metadata provided by Google APIs Discovery Service. Metadata provided by Discovery Service is cached, and won't be requested each time you load a client. Below, there is an example of loading a client for URL Shortener API.
googleapis
.discover('urlshortener', 'v1')
.execute(function(err, client) {
// make requests
});
Alternatively, you may like to configure the client to append an API key to all requests you are going to make. Once you load a client library, you can set an API key:
googleapis
.discover('urlshortener', 'v1')
.withApiKey('YOUR API KEY HERE')
.execute(function(err, client) {
// make requests
});
To learn more about API keys, please see the documentation.
The following sample loads a client for URL Shortener and retrieves the long url of the given short url:
googleapis.discover('urlshortener', 'v1').execute(function(err, client) {
client.urlshortener.url.get({ shortUrl: 'http://goo.gl/DdUKX' })
.execute(function(err, result) {
// result.longUrl contains the long url.
});
});
You can combine multiple requests in a single one by using batch requests.
var request1 =
client.plus.people.get({ userId: '+BurcuDogan' });
var request2 =
client.urlshortener.url.insert(null, { longUrl: 'http://goo.gl/A5492' });
// create from raw action name
var request3 = client.newRequest('urlshortener.url.list');
client
.newBatchRequest()
.add(request1)
.add(request2)
.add(request3)
.execute(function(err, results) {
});
This client comes with an OAuth2 client that allows you to retrieve an access token and refreshes the token and re-try the request seamlessly if token is expired. The basics of Google's OAuth 2.0 implementation is explained on Google Authorization and Authentication documentation.
A complete sample application that authorizes and authenticates with OAuth2.0
client is available at examples/oauth2.js
.
In order to ask for permissions from a user to retrieve an access token, you should redirect them to a consent page. In order to create a consent page URL:
var googleapis = require('googleapis'),
OAuth2Client = googleapis.OAuth2Client;
var oauth2Client =
new OAuth2Client(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
// generates a url that allows offline access and asks permissions
// for Google+ scope.
var url = oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: 'https://www.googleapis.com/auth/plus.me'
});
Once a user has given permissions on the consent page, Google will redirect the page to the redirect url you have provided with a code query parameter.
GET /oauthcallback?code={authorizationCode}
With the code returned, you can ask for an access token as shown below:
oauth2Client.getToken(code, function(err, tokens) {
// contains an access_token and optionally a refresh_token.
// save them permanently.
});
And you can start using oauth2Client to authorize and authenticate your requests to Google APIs with the retrieved tokens. If you provide a refresh_token, in cases when access_token is expired, it asks for a new access_token and replays the request.
Following sample retrieves Google+ profile of the authenticated user.
oauth2Client.credentials = {
access_token: 'ACCESS TOKEN HERE',
refresh_token: 'REFRESH TOKEN HERE'
};
client
.plus.people.get({ userId: 'me' })
.withAuthClient(oauth2Client)
.execute(callback);
google-api-nodejs-client
is licensed with Apache 2.0. Full license text is
available on COPYING file.
Before making any contributions, please sign one of the contributor license agreements below.
Fork the repo, develop and test your code changes.
Install all dependencies including development requirements by running:
$ npm install -d
Tests use mocha. To run all tests you can use
$ npm test
which looks for tests in the ./tests
directory.
Your code should honor the Google JavaScript Style Guide. You can use Closure Linter to detect style issues.
Submit a pull request. The repo owner will review your request. If it is approved, the change will be merged. If it needs additional work, the repo owner will respond with useful comments.
Before creating a pull request, please fill out either the individual or corporate Contributor License Agreement.
Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll add you to the official list of contributors and be able to accept your patches.
FAQs
Google APIs Client Library for Node.js
The npm package googleapis receives a total of 1,689,433 weekly downloads. As such, googleapis popularity was classified as popular.
We found that googleapis demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.
Security News
Biden's executive order pushes for AI-driven cybersecurity, software supply chain transparency, and stronger protections for federal and open source systems.